
import 'dotenv/config';
import db from './src/database/models/index';
const { Application, Interview, InterviewParticipant, InterviewEvaluation } = db;
import { Op } from 'sequelize';

async function testApprovalSync() {
    console.log('--- Testing Synchronized Approval Logic (Direct DB Simulation) ---');

    try {
        // Setup IDs for test (must exist in DB)
        const user1Id = 'fb9ba702-233b-4b3f-ba21-33bedec6209a'; // DD-ZM
        const user2Id = 'c3602348-c9bd-4938-83b2-acc3c62791aa'; // RBM

        // 1. Setup a test application
        console.log('\n1. Creating test application...');
        const app = await Application.create({
            applicationId: 'APP-' + Date.now(),
            registrationNumber: 'TEST-' + Date.now(),
            fullName: 'Test Applicant',
            applicantName: 'Test Applicant',
            email: 'test' + Date.now() + '@example.com',
            phone: '1234567890',
            businessType: 'Dealership',
            overallStatus: 'Level 1 Interview Pending',
            currentStage: 'Level 1 Approved', // Mocking stage
            zoneId: 'aedf5f64-3f95-4fa7-ac64-52c97cb330e7',
            regionId: 'a5ea0aa2-c26c-49a9-95fe-0dbd7283c125'
        });

        // 2. Create an interview with 2 participants
        console.log('2. Creating interview for Level 1...');
        const interview = await Interview.create({
            applicationId: app.id,
            level: 1,
            status: 'Scheduled',
            interviewType: 'Level 1 Interview'
        });

        const participant1 = await InterviewParticipant.create({
            interviewId: interview.id,
            userId: user1Id,
            roleInPanel: 'Interviewer'
        });

        const participant2 = await InterviewParticipant.create({
            interviewId: interview.id,
            userId: user2Id,
            roleInPanel: 'Interviewer'
        });

        console.log(`Interview created with ID: ${interview.id}`);

        // Decision logic
        async function submitDecision(userId: string, decision: string) {
            console.log(`\nSubmitting ${decision} for User: ${userId}...`);
            
            await InterviewEvaluation.create({
                interviewId: interview.id,
                evaluatorId: userId,
                recommendation: decision,
                decision: decision,
                remarks: 'Testing'
            });

            // Replicate the sync check from controller
            const participants = await InterviewParticipant.findAll({ where: { interviewId: interview.id } });
            const evaluations = await InterviewEvaluation.findAll({ where: { interviewId: interview.id } });

            const isFullyEvaluated = evaluations.length >= participants.length;
            console.log(`Evaluations: ${evaluations.length}/${participants.length}. Fully Evaluated: ${isFullyEvaluated}`);

            if (isFullyEvaluated) {
                console.log('Finalizing interview and updating application status...');
                await interview.update({ status: 'Completed' });
                
                const nextStatus = 'Level 1 Approved';
                await Application.update({ 
                    overallStatus: nextStatus,
                    currentStage: 'Level 1 Approved'
                }, { where: { id: app.id } });
                console.log(`Application status updated to: ${nextStatus}`);
            } else {
                console.log('Waiting for more evaluations. Application status remains unchanged.');
            }
        }

        // 3. First participant rejects
        await submitDecision(user1Id, 'Rejected');
        let currentApp = await Application.findByPk(app.id);
        console.log(`Current App Overall Status: ${currentApp.overallStatus}`);

        // 4. Second participant approves
        await submitDecision(user2Id, 'Approved');
        currentApp = await Application.findByPk(app.id);
        console.log(`Final App Overall Status: ${currentApp.overallStatus}`);

        // Cleanup
        console.log('\nCleaning up...');
        await InterviewEvaluation.destroy({ where: { interviewId: interview.id } });
        await InterviewParticipant.destroy({ where: { interviewId: interview.id } });
        await Interview.destroy({ where: { id: interview.id } });
        await Application.destroy({ where: { id: app.id } });

    } catch (error) {
        console.error('Test failed:', error);
    } finally {
        process.exit(0);
    }
}

testApprovalSync();
