import 'dotenv/config';
import db from './src/database/models/index.js';
const { Application, ApplicationStatusHistory, ApplicationProgress, QuestionnaireResponse, QuestionnaireQuestion, QuestionnaireOption, RequestParticipant, User, StageApprovalAction, DealerCode, Dealer } = (db as any).default || db;
import { Op } from 'sequelize';

const applicationId = '6139d6f9-f3c1-4e55-903b-3516d3a08955';

async function debugApp() {
    try {
        console.log('Step 1: Fetching main application record...');
        const application = await Application.findOne({
            where: {
                [Op.or]: [
                    { id: applicationId },
                    { applicationId: applicationId }
                ]
            }
        });

        if (!application) {
            console.log('Application not found.');
            return;
        }

        console.log('Step 2: Fetching status history...');
        const history = await application.getStatusHistory();
        console.log(`- Found ${history.length} records.`);

        console.log('Step 3: Fetching progress tracking...');
        const progress = await application.getProgressTracking();
        console.log(`- Found ${progress.length} records.`);

        console.log('Step 4: Fetching questionnaire responses (with nested)...');
        const responses = await QuestionnaireResponse.findAll({
            where: { applicationId: application.id },
            include: [
                {
                    model: QuestionnaireQuestion,
                    as: 'question',
                    include: [{ model: QuestionnaireOption, as: 'questionOptions' }]
                }
            ]
        });
        console.log(`- Found ${responses.length} responses.`);

        console.log('Step 5: Fetching participants...');
        const participants = await application.getParticipants({
             include: [{ model: User, as: 'user' }]
        });
        console.log(`- Found ${participants.length} participants.`);

        console.log('Step 6: Fetching stage approvals...');
        const approvals = await application.getStageApprovals();
        console.log(`- Found ${approvals.length} records.`);

        console.log('Step 7: Fetching DealerCode/Dealer...');
        const dealerCode = await application.getDealerCode();
        const dealer = await application.getDealer();
        console.log(`- DealerCode: ${!!dealerCode}, Dealer: ${!!dealer}`);

        console.log('Step 8: Constructing final object manually...');
        const finalObj = {
            ...application.toJSON(),
            statusHistory: history,
            progressTracking: progress,
            questionnaireResponses: responses,
            participants,
            stageApprovals: approvals,
            dealerCode,
            dealer
        };

        console.log('Step 9: JSON Serialization...');
        const start = Date.now();
        const json = JSON.stringify(finalObj);
        console.log(`- JSON Length: ${json.length} bytes`);
        console.log(`- Serialization took ${Date.now() - start}ms`);

        console.log('DONE!');
    } catch (error) {
        console.error('Error in debugApp:', error);
    } finally {
        process.exit();
    }
}

debugApp();
