import db from '../src/database/models/index.js';
import { ParticipantService } from '../src/services/ParticipantService.js';

async function run() {
    const fnfId = process.argv[2];
    if (!fnfId) {
        console.error('Usage: npx tsx check_participants.ts <fnfId>');
        process.exit(1);
    }

    console.log(`Checking participants for F&F: ${fnfId}`);

    try {
        const participants = await db.RequestParticipant.findAll({
            where: {
                requestId: fnfId,
                requestType: 'fnf'
            },
            include: [{ model: db.User, as: 'user', attributes: ['fullName', 'roleCode'] }]
        });

        console.log(`Found ${participants.length} database entries for participants.`);

        if (participants.length === 0) {
            console.log('No participants found in DB. Attempting manual backfill...');
            await ParticipantService.assignFnFParticipants(fnfId);

            const recheck = await db.RequestParticipant.findAll({
                where: { requestId: fnfId, requestType: 'fnf' }
            });
            console.log(`After backfill: Found ${recheck.length} participants.`);
        } else {
            participants.forEach((p: any) => {
                console.log(`- ${p.user?.fullName || 'Unknown'} (${p.user?.roleCode}), Type: ${p.participantType}`);
            });
        }
    } catch (error) {
        console.error('Error:', error);
    } finally {
        process.exit();
    }
}

run();
