import 'dotenv/config';
import db from '../src/database/models/index.js';
import bcrypt from 'bcryptjs';
import { syncLocationManagers, syncRegionManager, syncZoneManager } from '../src/modules/master/syncHierarchy.service.js';
import { resolveManagerCode } from '../src/services/userRoleCode.service.js';

const { Role, Zone, Region, State, District, User, UserRole } = db;

async function seed() {
    console.log('--- Seeding Comprehensive Golden Path Data ---');

    await db.sequelize.authenticate();
    await db.sequelize.sync({ alter: false });

    const hashedPassword = await bcrypt.hash('Admin@123', 10);

    // 1. Ensure Roles exist
    const roles = [
        { roleCode: 'NBH', roleName: 'National Business Head', category: 'NATIONAL' },
        { roleCode: 'DD Head', roleName: 'DD Head', category: 'NATIONAL' },
        { roleCode: 'ZBH', roleName: 'Zonal Business Head', category: 'ZONAL' },
        { roleCode: 'DD Lead', roleName: 'DD Lead', category: 'ZONAL' },
        { roleCode: 'RBM', roleName: 'Regional Business Manager', category: 'REGIONAL' },
        { roleCode: 'DD-ZM', roleName: 'DD Zonal Manager', category: 'ZONAL' },
        { roleCode: 'ASM', roleName: 'Area Sales Manager', category: 'AREA' },
        { roleCode: 'Super Admin', roleName: 'Super Admin', category: 'NATIONAL' },
        { roleCode: 'Finance', roleName: 'Finance', category: 'DEPARTMENT' },
        { roleCode: 'Dealer', roleName: 'Dealer', category: 'EXTERNAL' },
        { roleCode: 'DD Admin', roleName: 'DD Admin', category: 'ADMIN' },
        { roleCode: 'ARCHITECTURE', roleName: 'Architecture Team', category: 'DEPARTMENT' },
        { roleCode: 'FDD', roleName: 'FDD Team', category: 'EXTERNAL' },
        { roleCode: 'Legal Admin', roleName: 'Legal Admin', category: 'DEPARTMENT' },
        { roleCode: 'CEO', roleName: 'CEO', category: 'NATIONAL' },
        { roleCode: 'CCO', roleName: 'CCO', category: 'NATIONAL' },
        { roleCode: 'DD-AM', roleName: 'Dealer Development Area Manager', category: 'AREA' }
    ];

    for (const r of roles) {
        await Role.findOrCreate({ where: { roleCode: r.roleCode }, defaults: r });
    }

    const mapUserRole = async (userRec: any, roleCode: string, assignment: any = {}) => {
        const role = await Role.findOne({ where: { roleCode } });
        if (role) {
            const managerCode = await resolveManagerCode(role.id, roleCode, null);
            await UserRole.findOrCreate({
                where: { userId: userRec.id, roleId: role.id, ...assignment },
                defaults: {
                    userId: userRec.id,
                    roleId: role.id,
                    ...assignment,
                    managerCode,
                    isActive: true,
                    isPrimary: true
                }
            });
        }
    };

    // 2. Create Hierarchical Structure
    // Zones
    const zones = [
        { name: 'North Zone', code: 'ZONE-N' },
        { name: 'South Zone', code: 'ZONE-S' }
    ];
    const zoneMap: Record<string, any> = {};
    for (const z of zones) {
        const [zone] = await Zone.findOrCreate({ where: { name: z.name }, defaults: z });
        zoneMap[z.name] = zone;
    }

    // Regions
    const regions = [
        { name: 'NCR Region', zoneName: 'North Zone', code: 'NZ-R1' },
        { name: 'Punjab Region', zoneName: 'North Zone', code: 'NZ-R2' },
        { name: 'Karnataka Region', zoneName: 'South Zone', code: 'SZ-R1' },
        { name: 'Tamil Nadu Region', zoneName: 'South Zone', code: 'SZ-R2' }
    ];
    const regionMap: Record<string, any> = {};
    for (const r of regions) {
        const zone = zoneMap[r.zoneName];
        const [region] = await Region.findOrCreate({ 
            where: { name: r.name }, 
            defaults: { name: r.name, code: r.code, zoneId: zone.id } 
        });
        if (!region.code) {
            await region.update({ code: r.code });
        }
        regionMap[r.name] = region;
    }

    // 3. States & Districts (Mapping South Delhi to NCR)
    const ncrRegion = regionMap['NCR Region'];
    
    const [delhiState] = await State.findOrCreate({
        where: { name: 'DELHI' },
        defaults: { name: 'DELHI', zoneId: ncrRegion.zoneId }
    });

    const [southDelhi] = await District.findOrCreate({
        where: { name: 'South Delhi' },
        defaults: { 
            name: 'South Delhi', 
            stateId: delhiState.id, 
            regionId: ncrRegion.id, 
            zoneId: ncrRegion.zoneId, 
            isActive: true 
        }
    });

    // Ensure it's explicitly under NCR
    await southDelhi.update({ regionId: ncrRegion.id });

    console.log('✅ Mapping: South Delhi -> NCR Region');

    // 3. Create Key Management Users
    // National / Administrative
    const nationalUsers = [
        { email: 'yashwin@royalenfield.com', name: 'Yashwin', role: 'NBH' },
        { email: 'ganesh@royalenfield.com', name: 'ganesh', role: 'DD Head' },
        { email: 'finance@royalenfield.com', name: 'Finance Admin', role: 'Finance' },
        { email: 'admin@royalenfield.com', name: 'Super Admin', role: 'Super Admin' },
        { email: 'lince@royalenfield.com', name: 'Lince', role: 'DD Admin' },
        { email: 'fdd@royalenfield.com', name: 'FDD Team', role: 'FDD' },
        { email: 'legal@royalenfield.com', name: 'Legal Admin', role: 'Legal Admin' },
        { email: 'ceo@royalenfield.com', name: 'CEO', role: 'CEO' },
        { email: 'cco@royalenfield.com', name: 'CCO', role: 'CCO' },
    ];
    for (const u of nationalUsers) {
        const [user] = await User.findOrCreate({ 
            where: { email: u.email }, 
            defaults: { fullName: u.name, roleCode: u.role, password: hashedPassword, status: 'active' } 
        });
        await mapUserRole(user, u.role);
    }

    // Frontend Mock Users for Quick Login (Ensuring exact matches)
    const frontendMocks = [
        { email: 'jaya@royalenfield.com', name: 'Jaya', role: 'DD Lead', zone: 'North Zone' },
        { email: 'manav@royalenfield.com', name: 'manav', role: 'ZBH', zone: 'North Zone' },
        { email: 'piyush@royalenfield.com', name: 'piyush', role: 'DD-ZM', zone: 'North Zone' },
        { email: 'manish@royalenfield.com', name: 'manish', role: 'RBM', zone: 'North Zone' },
        { email: 'abhishek@royalenfield.com', name: 'abhishek', role: 'ASM', district: 'South Delhi' },
        { email: 'bharghav@gmail.com', name: 'Bharghav', role: 'DD-AM', district: 'South Delhi' }
    ];
    for (const m of frontendMocks) {
        const assignment: any = {};
        if (m.zone) assignment.zoneId = zoneMap[m.zone].id;
        if (m.district) {
            const d = await District.findOne({ where: { name: m.district } });
            if (d) {
                assignment.districtId = d.id;
                assignment.zoneId = d.zoneId;
                assignment.regionId = d.regionId;
            }
        }
        const [user] = await User.findOrCreate({ 
            where: { email: m.email }, 
            defaults: { fullName: m.name, roleCode: m.role, password: hashedPassword, status: 'active' } 
        });
        await mapUserRole(user, m.role, assignment);
    }

    // Zonal Business Heads (Additional)
    const zbhUsers: any[] = [];
    for (const u of zbhUsers) {
        const zone = zoneMap[u.zone];
        const [user] = await User.findOrCreate({ 
            where: { email: u.email }, 
            defaults: { fullName: u.name, roleCode: 'ZBH', password: hashedPassword, status: 'active' } 
        });
        await mapUserRole(user, 'ZBH', { zoneId: zone.id });
    }

    // Regional Managers (RBMs)
    const rbmUsers = [
        { email: 'manish@royalenfield.com', name: 'manish', region: 'NCR Region' }
    ];
    for (const u of rbmUsers) {
        const region = regionMap[u.region];
        const [user] = await User.findOrCreate({ 
            where: { email: u.email }, 
            defaults: { fullName: u.name, roleCode: 'RBM', password: hashedPassword, status: 'active' } 
        });
        await mapUserRole(user, 'RBM', { regionId: region.id, zoneId: region.zoneId });
    }

    // Zonal Managers (DD-ZM) - Assigned to Regions
    const zmUsers = [
        { email: 'piyush@royalenfield.com', name: 'piyush', region: 'NCR Region' }
    ];
    for (const u of zmUsers) {
        const region = regionMap[u.region];
        const [user] = await User.findOrCreate({ 
            where: { email: u.email }, 
            defaults: { fullName: u.name, roleCode: 'DD-ZM', password: hashedPassword, status: 'active' } 
        });
        await mapUserRole(user, 'DD-ZM', { regionId: region.id, zoneId: region.zoneId });
    }

    // ASMs (Assigned to Districts)
    const asmUsers = [
        { email: 'abhishek@royalenfield.com', name: 'abhishek', district: 'South Delhi' }
    ];
    for (const u of asmUsers) {
        const district = await District.findOne({ where: { name: u.district } });
        if (district) {
            const [user] = await User.findOrCreate({ 
                where: { email: u.email }, 
                defaults: { fullName: u.name, roleCode: 'ASM', password: hashedPassword, status: 'active' } 
            });
            await mapUserRole(user, 'ASM', { districtId: district.id, zoneId: district.zoneId, regionId: district.regionId });
        }
    }

    console.log('ℹ️ Dealer test profile seeding skipped (using internal users-only seed set).');

    console.log('--- Triggering Hierarchy Synchronization ---');
    // ... (rest same)

    console.log('--- Golden Path Seeding Complete ---');
}

seed().catch(err => {
    console.error(err);
    process.exit(1);
}).then(() => process.exit(0));
