const BASE_URL = 'http://localhost:5000/api';
const FINANCE_EMAIL = 'finance@royalenfield.com';
const PASSWORD = 'Admin@123';

async function simulateFullClearance() {
    try {
        console.log('--- STARTING COMPREHENSIVE F&F SIMULATION (16 DEPARTMENTS) ---');

        // 1. Login
        const loginRes = await fetch(`${BASE_URL}/auth/login`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ email: FINANCE_EMAIL, password: PASSWORD })
        });
        const loginData = await loginRes.json();
        const token = loginData.token;
        const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` };

        // 2. Resolve target F&F
        const res = await fetch(`${BASE_URL}/settlement/fnf`, { headers });
        const data = await res.json();
        const latestFnF = data.settlements[0];
        
        if (!latestFnF) {
            console.error('No F&F record found.');
            return;
        }
        const fnfId = latestFnF.id;
        console.log(`Targeting F&F: ${fnfId} for ${latestFnF.outlet?.name}`);

        // 3. Define departmental scenarios
        const scenarios = [
            { dept: 'Sales', type: 'Receivable', amount: 45000, desc: 'Pending vehicle stock dues' },
            { dept: 'Service', type: 'Payable', amount: 12000, desc: 'Unprocessed warranty claims' },
            { dept: 'Spares / Parts', type: 'Receivable', amount: 8500, desc: 'Missing spare parts inventory' },
            { dept: 'Warranty', type: 'Payable', amount: 3400, desc: 'Settled warranty credit' },
            { dept: 'Accounts', type: 'Receivable', amount: 1500, desc: 'Audit penalty' },
            { dept: 'Marketing', type: 'Payable', amount: 20000, desc: 'Signage reimbursement' }
        ];

        // 4. Add Line Items
        console.log('\nAdding financial line items...');
        for (const item of scenarios) {
            await fetch(`${BASE_URL}/settlement/fnf/${fnfId}/line-items`, {
                method: 'POST',
                headers,
                body: JSON.stringify({
                    itemType: item.type,
                    description: item.desc,
                    department: item.dept,
                    amount: item.amount
                })
            });
            console.log(`[+] Added ${item.type} for ${item.dept}: ₹${item.amount}`);
        }

        // 5. Submit Clearances for ALL 16 Departments
        console.log('\nSubmitting clearances for all 16 departments...');
        const allDepts = latestFnF.clearances;
        
        for (const clearance of allDepts) {
            const hasDues = scenarios.some(s => s.dept === clearance.department);
            
            await fetch(`${BASE_URL}/settlement/fnf/${fnfId}/clearances/${clearance.id}`, {
                method: 'PUT',
                headers,
                body: JSON.stringify({
                    status: 'Cleared', // Backend will auto-convert to 'NOC Submitted' or 'Dues Pending'
                    remarks: hasDues 
                        ? `Clearance submitted with outstanding dues as listed in calculations.` 
                        : `No dues found. Department NOC issued successfully.`,
                    supportingDocument: `https://re-dealer-onboard.s3.amazonaws.com/noc/${clearance.department.replace(/\s/g, '_')}_NOC.pdf`
                })
            });
            console.log(`[OK] Cleared ${clearance.department} (${hasDues ? 'With Dues' : 'Full NOC'})`);
        }

        // 6. Verify Final State
        const finalRes = await fetch(`${BASE_URL}/settlement/fnf/${fnfId}`, { headers });
        const finalData = await finalRes.json();
        const f = finalData.fnf;

        console.log('\n--- FINAL VERIFICATION ---');
        console.log(`Case Number: ${f.resignation?.resignationId || f.id}`);
        console.log(`Overall Status: ${f.status}`);
        console.log(`Overall Progress: ${f.progressPercentage}%`);
        console.log(`Net Settlement Amount: ₹${f.netAmount}`);
        console.log(`Departments with Dues: ${f.clearances.filter(c => c.status === 'Dues Pending').length}`);
        console.log(`Departments with NOC: ${f.clearances.filter(c => c.status === 'NOC Submitted').length}`);
        
        console.log('\nUI CHECKLIST:');
        console.log('1. Verify Step 2 of progress bar is Green (Completed).');
        console.log('2. Verify Step 3 (Finance Summary) is Blue (In Progress).');
        console.log('3. Verify Status Badges in table: 6 Red (Dues Pending), 10 Green (NOC Submitted).');
        console.log('4. Verify Net Amount matches the sum of added items.');

    } catch (error) {
        console.error('Simulation Failed:', error);
    }
}

simulateFullClearance();
