import db from '../database/models/index.js';
const { Application, User, Outlet, Dealer, DealerCode } = db;
import { Op } from 'sequelize';

async function test() {
    console.log('--- Starting Multi-Outlet Support Test ---');

    const email = `test_dealer_multi_${Date.now()}@example.com`;
    const phone = '9876543210';
    
    try {
        // 1. Initial Application for City X
        console.log('1. Submitting first application for City X...');
        const app1 = await Application.create({
            applicationId: `APP-X-${Date.now()}`,
            applicantName: 'Test Dealer',
            email,
            phone,
            businessType: 'Dealership',
            city: 'City X',
            preferredLocation: 'Location X',
            overallStatus: 'Pending',
            currentStage: 'DD',
            zoneId: null,
            regionId: null
        });
        console.log('Success: Application 1 created.');

        // 2. Duplicate Application for SAME Location
        console.log('2. Attempting duplicate application for City X...');
        const existingApp = await Application.findOne({ 
            where: { 
                email,
                city: 'City X',
                preferredLocation: 'Location X',
                overallStatus: { [Op.ne]: 'Rejected' }
            } 
        });
        
        if (existingApp) {
            console.log('Correct: Detected duplicate application for same location.');
        } else {
            console.error('Error: Failed to detect duplicate location!');
        }

        // 3. New Application for DIFFERENT Location (City Y)
        console.log('3. Submitting application for City Y...');
        const app2 = await Application.create({
            applicationId: `APP-Y-${Date.now()}`,
            applicantName: 'Test Dealer',
            email,
            phone,
            businessType: 'Dealership',
            city: 'City Y',
            preferredLocation: 'Location Y',
            overallStatus: 'Pending',
            currentStage: 'DD',
            zoneId: null,
            regionId: null
        });
        console.log('Success: Application 2 created for different location.');

        // 4. Onboard Application 1 (Simulated step)
        console.log('4. Onboarding Application 1...');
        const dCode1 = await DealerCode.create({
            dealerCode: `CODE-X-${Date.now()}`,
            applicationId: app1.id
        });
        
        const dealer1 = await Dealer.create({
            applicationId: app1.id,
            dealerCodeId: dCode1.id,
            legalName: 'Test Dealer X Ltd',
            businessName: 'Test Dealer - X',
            constitutionType: 'Partnership',
            status: 'Active'
        });

        const user = await User.create({
            fullName: 'Test Dealer',
            email,
            password: 'hashed_password',
            roleCode: 'Dealer',
            dealerId: dealer1.id,
            status: 'active'
        });

        // Current Logic in dealer.controller.ts for outlet 1
        const outlet1 = await Outlet.create({
            code: `OUT-X-${Date.now()}`,
            name: `${app1.applicantName} - ${app1.city}`,
            type: 'Dealership',
            address: 'Address X',
            city: 'City X',
            state: 'State X',
            pincode: '123456',
            status: 'Active',
            establishedDate: new Date(),
            dealerId: user.id,
            region: 'Central',
            zone: 'National'
        });
        console.log('Success: Application 1 onboarded.');

        // 5. Onboard Application 2 (Simulation of our fix)
        console.log('5. Onboarding Application 2 (sharing same user)...');
        const dCode2 = await DealerCode.create({
            dealerCode: `CODE-Y-${Date.now()}`,
            applicationId: app2.id
        });

        const dealer2 = await Dealer.create({
            applicationId: app2.id,
            dealerCodeId: dCode2.id,
            legalName: 'Test Dealer Y Ltd',
            businessName: 'Test Dealer - Y',
            constitutionType: 'Partnership',
            status: 'Active'
        });

        // Update existing user with new dealerId (Latest)
        await user.update({ dealerId: dealer2.id });

        // Our Fix in dealer.controller.ts: Check for outlet for THIS application/city
        let existingOutletForThisApp = await Outlet.findOne({ 
            where: { 
                dealerId: user.id,
                name: { [Op.like]: `%${app2.city}%` }
            } 
        });

        if (!existingOutletForThisApp) {
            const outlet2 = await Outlet.create({
                code: `OUT-Y-${Date.now()}`,
                name: `${app2.applicantName} - ${app2.city}`,
                type: 'Dealership',
                address: 'Address Y',
                city: 'City Y',
                state: 'State Y',
                pincode: '654321',
                status: 'Active',
                establishedDate: new Date(),
                dealerId: user.id,
                region: 'Central',
                zone: 'National'
            });
            console.log('Success: Outlet 2 created for City Y.');
        } else {
            console.error('Error: Outlet for City Y already exists wrongly!');
        }

        // 6. Final Check
        const outletCount = await Outlet.count({ where: { dealerId: user.id } });
        console.log(`Final Verification: User ${email} has ${outletCount} outlets total.`);
        
        if (outletCount === 2) {
            console.log('TEST PASSED: Multi-outlet support verified.');
        } else {
            console.error(`TEST FAILED: Expected 2 outlets, found ${outletCount}.`);
        }

    } catch (error) {
        console.error('Test error:', error);
    } finally {
        process.exit();
    }
}

test();
