import db from './src/database/models/index.js';
import { APPLICATION_STATUS } from './src/common/config/constants.js';
import { syncApplicationProgress } from './src/common/utils/progress.js';

async function repair() {
    const app = await db.Application.findOne({ where: { applicationId: 'APP-2026-D444A1' } });
    if (!app) {
        console.log('Application not found');
        return;
    }

    // 1. Ensure LoiRequest exists
    const [request, created] = await db.LoiRequest.findOrCreate({
        where: { applicationId: app.id },
        defaults: {
            requestedBy: null, // System initiated via FDD completion
            status: 'In Progress'
        }
    });
    console.log(`LoiRequest ${created ? 'Created' : 'Found'}`);

    // 2. Ensure Finance Approval entry exists in LOI
    await db.LoiApproval.findOrCreate({
        where: { requestId: request.id, approverRole: 'Finance' },
        defaults: { action: 'Pending', level: 1 }
    });

    // 3. Sync Progress Record (This creates the missing LOI Approval progress item)
    await syncApplicationProgress(app.id, APPLICATION_STATUS.LOI_IN_PROGRESS);
    console.log('Progress records synchronized.');

    process.exit(0);
}

repair();
