#!/usr/bin/env node

/**
 * TDD Tests for Bulk Operations in Concurrent Editing
 */

const { TestRunner } = require('./test_runner.js');
const runner = new TestRunner();

// Test bulk operations for concurrent editing
runner.describe('Bulk Operations for Concurrent Editing', () => {

    runner.it('should successfully accept all editing sessions in bulk', async () => {
        // Load editor
        delete require.cache[require.resolve('/home/worsch/markitect_project/markitect/static/editor.js')];
        require('/home/worsch/markitect_project/markitect/static/editor.js');

        if (global.SectionManager) {
            const manager = new global.SectionManager();
            const sections = manager.createSectionsFromMarkdown('# Section 1\n\nContent 1\n\n# Section 2\n\nContent 2\n\n# Section 3\n\nContent 3');

            // Start editing multiple sections
            manager.startEditing(sections[0].id);
            manager.startEditing(sections[1].id);
            manager.startEditing(sections[2].id);

            // Modify them
            manager.updateContent(sections[0].id, '# Section 1\n\nModified 1');
            manager.updateContent(sections[1].id, '# Section 2\n\nModified 2');
            manager.updateContent(sections[2].id, '# Section 3\n\nModified 3');

            // Bulk accept
            const results = manager.acceptAllEditingSessions();

            // All should be successfully accepted
            runner.expect(results.length).toBe(3);
            runner.expect(results.every(r => r.success)).toBeTruthy();

            // None should be editing anymore
            runner.expect(sections.every(s => !s.isEditing())).toBeTruthy();

            // All should have the modified content
            runner.expect(sections[0].currentMarkdown).toBe('# Section 1\n\nModified 1');
            runner.expect(sections[1].currentMarkdown).toBe('# Section 2\n\nModified 2');
            runner.expect(sections[2].currentMarkdown).toBe('# Section 3\n\nModified 3');
        }
    });

    runner.it('should successfully cancel all editing sessions in bulk', async () => {
        if (global.SectionManager) {
            const manager = new global.SectionManager();
            const sections = manager.createSectionsFromMarkdown('# Section 1\n\nContent 1\n\n# Section 2\n\nContent 2');

            // Start editing
            manager.startEditing(sections[0].id);
            manager.startEditing(sections[1].id);

            // Modify them
            manager.updateContent(sections[0].id, '# Section 1\n\nThis will be cancelled');
            manager.updateContent(sections[1].id, '# Section 2\n\nThis will be cancelled');

            // Bulk cancel
            const results = manager.cancelAllEditingSessions();

            // All should be successfully cancelled
            runner.expect(results.length).toBe(2);
            runner.expect(results.every(r => r.success)).toBeTruthy();

            // None should be editing anymore
            runner.expect(sections.every(s => !s.isEditing())).toBeTruthy();

            // All should have reverted to original content
            runner.expect(sections[0].currentMarkdown).toBe('# Section 1\n\nContent 1');
            runner.expect(sections[1].currentMarkdown).toBe('# Section 2\n\nContent 2');
        }
    });

    runner.it('should successfully stop all editing sessions with state preservation', async () => {
        if (global.SectionManager) {
            const manager = new global.SectionManager();
            const sections = manager.createSectionsFromMarkdown('# Section 1\n\nContent 1\n\n# Section 2\n\nContent 2');

            // Start editing
            manager.startEditing(sections[0].id);
            manager.startEditing(sections[1].id);

            // Modify them
            manager.updateContent(sections[0].id, '# Section 1\n\nPending changes 1');
            manager.updateContent(sections[1].id, '# Section 2\n\nPending changes 2');

            // Bulk stop (preserve changes as pending)
            const results = manager.stopAllEditingSessions();

            // All should be successfully stopped
            runner.expect(results.length).toBe(2);
            runner.expect(results.every(r => r.success)).toBeTruthy();

            // None should be editing anymore
            runner.expect(sections.every(s => !s.isEditing())).toBeTruthy();

            // All should have modified state (pending changes preserved)
            runner.expect(sections.every(s => s.state === 'modified')).toBeTruthy();
            runner.expect(sections[0].pendingMarkdown).toBe('# Section 1\n\nPending changes 1');
            runner.expect(sections[1].pendingMarkdown).toBe('# Section 2\n\nPending changes 2');
        }
    });

    runner.it('should provide detailed concurrent editing status', async () => {
        if (global.SectionManager) {
            const manager = new global.SectionManager();
            const sections = manager.createSectionsFromMarkdown('# Section 1\n\nContent 1\n\n# Section 2\n\nContent 2\n\n# Section 3\n\nContent 3');

            // Start editing some sections
            manager.startEditing(sections[0].id);
            manager.startEditing(sections[2].id);

            // Modify one
            manager.updateContent(sections[0].id, '# Section 1\n\nModified');

            // Get concurrent editing status
            const status = manager.getConcurrentEditingStatus();

            runner.expect(status.totalSections).toBe(3);
            runner.expect(status.concurrentSessions.editingCount).toBe(2);
            runner.expect(status.concurrentSessions.editing.length).toBe(2);
            runner.expect(status.systemState.allowsConcurrentEditing).toBeTruthy();
            runner.expect(status.systemState.activeSessionCount).toBe(2);

            // Check specific editing session details
            const editingSession = status.concurrentSessions.editing.find(s => s.id === sections[0].id);
            runner.expect(editingSession).toBeTruthy();
            runner.expect(editingSession.hasUnsavedChanges).toBeTruthy();
        }
    });

    runner.it('should handle conflict detection and resolution', async () => {
        if (global.SectionManager) {
            const manager = new global.SectionManager();
            const sections = manager.createSectionsFromMarkdown('# Similar Heading\n\nContent 1\n\n# Similar Heading\n\nContent 2');

            // Start editing both similar sections
            manager.startEditing(sections[0].id);
            manager.startEditing(sections[1].id);

            // Test conflict resolution
            const conflictResult = manager.resolveEditingConflicts(sections[0].id, [sections[1].id]);

            runner.expect(conflictResult.resolved).toBeTruthy();
            runner.expect(Array.isArray(conflictResult.conflicts)).toBeTruthy();
            runner.expect(Array.isArray(conflictResult.resolutions)).toBeTruthy();
        }
    });

    runner.it('should handle bulk operations with mixed success/failure scenarios', async () => {
        if (global.SectionManager) {
            const manager = new global.SectionManager();
            const sections = manager.createSectionsFromMarkdown('# Section 1\n\nContent 1\n\n# Section 2\n\nContent 2');

            // Start editing one section
            manager.startEditing(sections[0].id);
            manager.updateContent(sections[0].id, '# Section 1\n\nModified');

            // Try bulk accept when only one is editing
            const results = manager.acceptAllEditingSessions();

            runner.expect(results.length).toBe(1);
            runner.expect(results[0].success).toBeTruthy();
            runner.expect(results[0].sectionId).toBe(sections[0].id);
        }
    });

    runner.it('should emit proper events for bulk operations', async () => {
        if (global.SectionManager) {
            const manager = new global.SectionManager();
            const sections = manager.createSectionsFromMarkdown('# Section 1\n\nContent 1\n\n# Section 2\n\nContent 2');

            let bulkAcceptFired = false;
            let bulkCancelFired = false;
            let bulkStopFired = false;

            // Listen for bulk events
            manager.on('bulk-accept-completed', () => { bulkAcceptFired = true; });
            manager.on('bulk-cancel-completed', () => { bulkCancelFired = true; });
            manager.on('bulk-stop-completed', () => { bulkStopFired = true; });

            // Test bulk accept event
            manager.startEditing(sections[0].id);
            manager.acceptAllEditingSessions();
            runner.expect(bulkAcceptFired).toBeTruthy();

            // Test bulk cancel event
            manager.startEditing(sections[1].id);
            manager.cancelAllEditingSessions();
            runner.expect(bulkCancelFired).toBeTruthy();

            // Test bulk stop event
            manager.startEditing(sections[0].id);
            manager.stopAllEditingSessions();
            runner.expect(bulkStopFired).toBeTruthy();
        }
    });

    runner.it('should calculate content similarity correctly', async () => {
        if (global.SectionManager) {
            const manager = new global.SectionManager();

            // Test identical content
            const similarity1 = manager.calculateContentSimilarity('# Same Heading', '# Same Heading');
            runner.expect(similarity1).toBe(1);

            // Test completely different content
            const similarity2 = manager.calculateContentSimilarity('# Different Heading', '## Another Topic');
            runner.expect(similarity2).toBeLessThan(0.5);

            // Test similar content
            const similarity3 = manager.calculateContentSimilarity('# Introduction to JavaScript', '# Introduction to Programming');
            runner.expect(similarity3).toBeGreaterThan(0.3);
            runner.expect(similarity3).toBeLessThan(1);
        }
    });
});

// Run the tests
if (require.main === module) {
    console.log('⚡ Running TDD Tests for Bulk Operations in Concurrent Editing');
    runner.run().then(() => {
        console.log('✅ Bulk operations test run complete!');
    });
}

module.exports = runner;