import db from '../database/models/index.js';
import { v4 as uuidv4 } from 'uuid';
import fs from 'fs';

const verifyScoring = async () => {
    try {
        console.log('Verifying Questionnaire Scoring...');

        // Sync DB to ensure 'score' column exists
        await db.sequelize.sync({ alter: true });

        // 1. Create a dummy test application
        const appId = uuidv4();
        const testApp = await db.Application.create({
            applicationId: `TEST-${Date.now()}`,
            applicantName: 'Test Scorer',
            email: 'test.scorer@example.com',
            phone: '1234567890',
            businessType: 'Dealership',
            currentStage: 'DD',
            overallStatus: 'Questionnaire Pending',
            score: 0
        });

        console.log(`Created Test Application: ${testApp.applicationId} (${testApp.id})`);

        // 2. Fetch Active Questionnaire Questions
        const questionnaire = await db.Questionnaire.findOne({
            where: { isActive: true },
            include: [{ model: db.QuestionnaireQuestion, as: 'questions' }]
        });

        if (!questionnaire) throw new Error('No active questionnaire found');

        // 3. Construct Responses to get a specific score
        // We will target:
        // - "Educational Qualification": "Post Graduate" (Score: 15)
        // - "Do you own a property...": "Yes" (Score: 10)
        // - All others: Non-scoring or first option (usually > 0)

        const responses = questionnaire.questions.map((q: any) => {
            let value = "Test Answer"; // Default for text/file

            if (q.questionText === "Educational Qualification") {
                value = "Post Graduate";
            } else if (q.questionText === "Do you own a property in proposed location?") {
                value = "Yes";
            } else if (q.inputType === 'select' || q.inputType === 'radio') {
                // Pick first option if not targeting specific score
                const opts = typeof q.options === 'string' ? JSON.parse(q.options) : q.options;
                if (opts && opts.length > 0) {
                    value = opts[0].text || opts[0];
                }
            }

            return {
                questionId: q.id,
                value: value
            };
        });

        console.log('Submitting responses...');

        // 4. Submit to API (assuming local server running on 5000)
        try {
            const res = await fetch('http://localhost:5000/api/questionnaire/public/submit', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    applicationId: testApp.applicationId,
                    responses: responses
                })
            });
            const data: any = await res.json();
            console.log('API Response:', data);
        } catch (apiError: any) {
            console.error('API Error:', apiError.message);
            fs.writeFileSync('verification_result.txt', `FAILURE: API Error - ${apiError.message}`);
            process.exit(1);
        }

        // 5. Check Score in DB
        const updatedApp = await db.Application.findByPk(testApp.id);
        console.log(`New Score: ${updatedApp.score}`);
        console.log(`New Status: ${updatedApp.overallStatus}`);

        // Write result to file
        if (updatedApp.score >= 25) {
            console.log('SUCCESS: Score updated!');
            fs.writeFileSync('verification_result.txt', `SUCCESS: Score ${updatedApp.score} matched expectation (>= 25)`);
        } else {
            console.error('FAILURE: Score mismatch.');
            fs.writeFileSync('verification_result.txt', `FAILURE: Score ${updatedApp.score} mismatch (expected >= 25)`);
            process.exit(1);
        }

        // Cleanup
        await testApp.destroy();

    } catch (error: any) {
        console.error('Verification failed:', error);
        fs.writeFileSync('verification_result.txt', `FAILURE: Script Error - ${error.message}`);
        process.exit(1);
    } finally {
        // await db.sequelize.close(); 
    }
};

verifyScoring();
