/**
 * Test script for image comparison functionality
 * Run with: node test_image_comparison.js
 */

// Mock context and test data
const mockCtx = {
    meta: { user: { userId: 'test-user-123' } },
    getObject: (objectName) => ({
        find: async (filters) => {
            console.log(`[Mock] Finding ${objectName} with filters:`, filters);
            
            // Mock image materials
            if (objectName === 'pepsico_material') {
                return [
                    {
                        _id: 'material-1',
                        name: 'test-image.jpg',
                        pepsico_material_approval: 'approval-123',
                        material: 'file-current-123',
                        material_original: 'file-original-123',
                        material_one_drive_history: ['file-v1-123', 'file-v2-123', 'file-current-123'],
                        extension_type: 'jpg'
                    }
                ];
            }
            return [];
        },
        directUpdate: async (id, data) => {
            console.log(`[Mock] Updating ${objectName} ${id}:`, data);
            return { success: true };
        }
    }),
    logger: {
        info: async (msg, data) => console.log('[Logger Info]', msg, data),
        error: async (msg, data) => console.error('[Logger Error]', msg, data)
    }
};

// Test functions
async function testImageMaterialFiltering() {
    console.log('\n=== Testing Image Material Filtering ===');
    
    const { getImageMaterials } = require('./src/methods/image_comparison');
    
    try {
        const materials = await getImageMaterials(mockCtx, 'approval-123');
        console.log('✓ Found image materials:', materials.length);
        console.log('Materials:', materials);
        return true;
    } catch (error) {
        console.error('✗ Test failed:', error.message);
        return false;
    }
}

async function testVersionRetrieval() {
    console.log('\n=== Testing Version Retrieval ===');
    
    const { getMaterialVersions } = require('./src/methods/image_comparison');
    
    const mockMaterial = {
        _id: 'material-1',
        material: 'file-current-123',
        material_original: 'file-original-123',
        material_one_drive_history: ['file-v1-123', 'file-v2-123', 'file-current-123']
    };
    
    try {
        const versions = await getMaterialVersions(mockCtx, mockMaterial);
        console.log('✓ Retrieved versions:');
        console.log('  Current:', versions.current);
        console.log('  Previous:', versions.previous);
        console.log('  Current URL:', versions.currentUrl);
        console.log('  Previous URL:', versions.previousUrl);
        return true;
    } catch (error) {
        console.error('✗ Test failed:', error.message);
        return false;
    }
}

async function testDataPreparation() {
    console.log('\n=== Testing Data Preparation ===');
    
    const { prepareImageComparisonData } = require('./src/methods/image_comparison');
    
    const mockMaterial = {
        _id: 'material-1',
        name: 'test-image.jpg',
        pepsico_material_approval: 'approval-123',
        extension_type: 'jpg'
    };
    
    const mockVersions = {
        current: 'file-current-123',
        previous: 'file-v2-123',
        currentUrl: 'http://example.com/current',
        previousUrl: 'http://example.com/previous'
    };
    
    try {
        const data = await prepareImageComparisonData(mockCtx, mockMaterial, mockVersions);
        console.log('✓ Prepared data:');
        console.log(JSON.stringify(data, null, 2));
        return true;
    } catch (error) {
        console.error('✗ Test failed:', error.message);
        return false;
    }
}

async function testModifiedSubmissionDetection() {
    console.log('\n=== Testing Modified Submission Detection ===');
    
    const { isModifiedSubmission } = require('./src/methods/image_comparison');
    
    const testCases = [
        { current_step: 'draft', expected: false },
        { current_step: 'submitter_revisions', expected: true },
        { current_step: 'ai_review', expected: false },
        { current_step: 'departmental_review', expected: false }
    ];
    
    let allPassed = true;
    
    for (const testCase of testCases) {
        const result = isModifiedSubmission(testCase);
        const passed = result === testCase.expected;
        
        if (passed) {
            console.log(`✓ Step '${testCase.current_step}': ${result} (expected: ${testCase.expected})`);
        } else {
            console.log(`✗ Step '${testCase.current_step}': ${result} (expected: ${testCase.expected})`);
            allPassed = false;
        }
    }
    
    return allPassed;
}

// Run all tests
async function runTests() {
    console.log('================================');
    console.log('Image Comparison Feature Tests');
    console.log('================================');
    
    const results = [];
    
    results.push(await testModifiedSubmissionDetection());
    results.push(await testImageMaterialFiltering());
    results.push(await testVersionRetrieval());
    results.push(await testDataPreparation());
    
    console.log('\n=== Test Summary ===');
    const passed = results.filter(r => r).length;
    const total = results.length;
    console.log(`Passed: ${passed}/${total}`);
    
    if (passed === total) {
        console.log('✓ All tests passed!');
    } else {
        console.log('✗ Some tests failed.');
    }
}

// Only run if executed directly
if (require.main === module) {
    runTests().catch(console.error);
}

module.exports = { runTests };
