import db from './src/database/models/index.js';
import { APPLICATION_STATUS, APPLICATION_STAGES } from './src/common/config/constants.js';

async function reset() {
    // List of application IDs provided in previous queries
    const appIds = ['APP-2026-D444A1', 'APP-2026-2DC97C']; 

    for (const id of appIds) {
        const app = await db.Application.findOne({ where: { applicationId: id } });
        if (!app) continue;

        console.log(`Resetting application ${id}...`);

        // 1. Delete future stage records
        const loiReq = await db.LoiRequest.findOne({ where: { applicationId: app.id } });
        if (loiReq) {
            await db.LoiApproval.destroy({ where: { requestId: loiReq.id } });
            await db.LoiDocumentGenerated.destroy({ where: { requestId: loiReq.id } });
            await loiReq.destroy();
        }

        const loaReq = await db.LoaRequest.findOne({ where: { applicationId: app.id } });
        if (loaReq) {
            await db.LoaApproval.destroy({ where: { requestId: loaReq.id } });
            await loaReq.destroy();
        }

        // 2. Delete FDD Reports and reset assignment
        const assignments = await db.FddAssignment.findAll({ where: { applicationId: app.id } });
        for (const ass of assignments) {
            await db.FddReport.destroy({ where: { assignmentId: ass.id } });
            await ass.update({ status: 'Assigned' });
        }

        // 3. Reset Application status
        await app.update({
            overallStatus: 'FDD Verification',
            currentStage: 'FDD',
            progressPercentage: 70
        });

        // 4. Reset Progress Tracker
        await db.ApplicationProgress.destroy({ 
            where: { 
                applicationId: app.id,
                stageName: ['LOI Approval', 'Security Deposit', 'LOI Issue', 'Dealer Code Generation', 'Architecture Team Assigned', 'Statutory GST']
            } 
        });

        await db.ApplicationProgress.upsert({
            applicationId: app.id,
            stageName: 'FDD',
            stageOrder: 8,
            status: 'active',
            completionPercentage: 70
        });

        console.log(`Application ${id} is now back to FDD stage.`);
    }

    process.exit(0);
}

reset();
