#!/usr/bin/env node

/**
 * TDD Tests for Multiple Concurrent Editing Sessions Support
 */

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

// Test multiple concurrent editing sessions functionality
runner.describe('Multiple Concurrent Editing Sessions Support', () => {

    runner.it('should allow editing multiple sections simultaneously', 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);

            // All sections should be in editing state
            runner.expect(sections[0].isEditing()).toBeTruthy();
            runner.expect(sections[1].isEditing()).toBeTruthy();
            runner.expect(sections[2].isEditing()).toBeTruthy();
        }
    });

    runner.it('should track all currently editing sessions', 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');

            // Initially no editing sessions
            const initialStatus = manager.getGlobalStatus();
            runner.expect(initialStatus.editingSections.length).toBe(0);

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

            // Should track both editing sessions
            const editingStatus = manager.getGlobalStatus();
            runner.expect(editingStatus.editingSections.length).toBe(2);
            runner.expect(editingStatus.editingSections.includes(sections[0].id)).toBeTruthy();
            runner.expect(editingStatus.editingSections.includes(sections[1].id)).toBeTruthy();
        }
    });

    runner.it('should handle concurrent content updates without conflicts', 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 both sections
            manager.startEditing(sections[0].id);
            manager.startEditing(sections[1].id);

            // Update content in both sections
            manager.updateContent(sections[0].id, '# Section 1\n\nModified content 1');
            manager.updateContent(sections[1].id, '# Section 2\n\nModified content 2');

            // Both should have updated content
            runner.expect(sections[0].editingMarkdown).toBe('# Section 1\n\nModified content 1');
            runner.expect(sections[1].editingMarkdown).toBe('# Section 2\n\nModified content 2');
        }
    });

    runner.it('should support selective accept/cancel for concurrent sessions', 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 both sections
            manager.startEditing(sections[0].id);
            manager.startEditing(sections[1].id);

            // Modify both
            manager.updateContent(sections[0].id, '# Section 1\n\nAccepted content');
            manager.updateContent(sections[1].id, '# Section 2\n\nCancelled content');

            // Accept first, cancel second
            manager.acceptChanges(sections[0].id);
            manager.cancelChanges(sections[1].id);

            // First should have new content, second should revert
            runner.expect(sections[0].currentMarkdown).toBe('# Section 1\n\nAccepted content');
            runner.expect(sections[1].currentMarkdown).toBe('# Section 2\n\nContent 2');

            // Only first should be in editing state
            runner.expect(sections[0].isEditing()).toBeFalsy();
            runner.expect(sections[1].isEditing()).toBeFalsy();
        }
    });

    runner.it('should maintain session isolation (changes in one don\'t affect others)', 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 all three
            manager.startEditing(sections[0].id);
            manager.startEditing(sections[1].id);
            manager.startEditing(sections[2].id);

            // Modify only the first one
            manager.updateContent(sections[0].id, '# Section 1\n\nOnly this changed');

            // Other sections should remain unchanged
            runner.expect(sections[1].editingMarkdown).toBe('# Section 2\n\nContent 2');
            runner.expect(sections[2].editingMarkdown).toBe('# Section 3\n\nContent 3');

            // Only first should show as modified
            runner.expect(sections[0].editingMarkdown).toBe('# Section 1\n\nOnly this changed');
        }
    });

    runner.it('should support bulk operations on concurrent sessions', 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');

            // Check if bulk methods exist
            const hasBulkAccept = typeof manager.acceptAllEditingSessions === 'function';
            const hasBulkCancel = typeof manager.cancelAllEditingSessions === 'function';
            const hasStopAllEditing = typeof manager.stopAllEditingSessions === 'function';

            // These are advanced features - if they exist, they should work
            if (hasBulkAccept && hasBulkCancel && hasStopAllEditing) {
                runner.expect(hasBulkAccept).toBeTruthy();
                runner.expect(hasBulkCancel).toBeTruthy();
                runner.expect(hasStopAllEditing).toBeTruthy();
            } else {
                // Basic functionality is acceptable
                runner.expect(true).toBeTruthy();
            }
        }
    });

    runner.it('should handle DOM rendering for multiple concurrent editors', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            const sections = manager.createSectionsFromMarkdown('# Section 1\n\nContent 1\n\n# Section 2\n\nContent 2');

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

            // Both should have editor containers in DOM
            const editorContainers = container.querySelectorAll('.ui-edit-editor-container, .ui-edit-image-editor-container');
            runner.expect(editorContainers.length).toBeGreaterThanOrEqual(1); // At least one should be visible

            // The renderer's editingSections set should track multiple sessions
            runner.expect(renderer.editingSections.size).toBeGreaterThanOrEqual(1);
        }
    });

    runner.it('should prevent conflicting operations during concurrent editing', async () => {
        if (global.SectionManager) {
            const manager = new global.SectionManager();
            const sections = manager.createSectionsFromMarkdown('# Section 1\n\nContent 1');

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

            // Attempting to start editing again should not cause errors
            try {
                manager.startEditing(sections[0].id);
                runner.expect(true).toBeTruthy(); // Should handle gracefully
            } catch (error) {
                runner.expect(false).toBeTruthy(); // Should not throw
            }

            // Section should still be in editing state
            runner.expect(sections[0].isEditing()).toBeTruthy();
        }
    });

    runner.it('should support concurrent session status reporting', 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');

            // Global status should reflect concurrent editing
            const status = manager.getGlobalStatus();
            runner.expect(status.state).toBe('editing');
            runner.expect(status.editingSections.length).toBe(2);
            runner.expect(status.hasModifications).toBeTruthy();

            // Section status should show individual states
            const sectionStatuses = manager.getSectionStatus();
            const editingCount = sectionStatuses.filter(s => s.isEditing).length;
            runner.expect(editingCount).toBe(2);
        }
    });
});

// Run the tests
if (require.main === module) {
    console.log('👥 Running TDD Tests for Multiple Concurrent Editing Sessions');
    runner.run().then(() => {
        console.log('✅ Concurrent editing test run complete!');
    });
}

module.exports = runner;