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';

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

async function resetAndSeed() {
    console.log('--- REFRESHING DATABASE (DROP & RECREATE) ---');

    await db.sequelize.authenticate();
    
    // WARNING: This drops all tables!
    await db.sequelize.sync({ force: true });
    console.log('Database schema recreated.');

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

    // 1. Roles
    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' }
    ];
    for (const r of roles) await Role.create(r);

    // 2. Structure
    const zoneN = await Zone.create({ name: 'North Zone', code: 'ZONE-N' });
    const zoneS = await Zone.create({ name: 'South Zone', code: 'ZONE-S' });

    const ncr = await Region.create({ name: 'NCR Region', zoneId: zoneN.id });
    const kar = await Region.create({ name: 'Karnataka Region', zoneId: zoneS.id });

    const delhi = await State.create({ name: 'DELHI', zoneId: zoneN.id });
    const karnataka = await State.create({ name: 'KARNATAKA', zoneId: zoneS.id });

    const sDelhi = await District.create({ name: 'South Delhi', stateId: delhi.id, regionId: ncr.id, zoneId: zoneN.id, isActive: true });
    const blr = await District.create({ name: 'Bangalore Urban', stateId: karnataka.id, regionId: kar.id, zoneId: zoneS.id, isActive: true });

    // 3. Users
    const users = [
        { email: 'admin@royalenfield.com', fullName: 'Super Admin', roleCode: 'Super Admin', password: hashedPassword, status: 'active' },
        { email: 'piyush@royalenfield.com', fullName: 'piyush', roleCode: 'DD-ZM', password: hashedPassword, status: 'active' },
        { email: 'manish@royalenfield.com', fullName: 'manish', roleCode: 'RBM', password: hashedPassword, status: 'active' },
        { email: 'manav@royalenfield.com', fullName: 'manav', roleCode: 'ZBH', password: hashedPassword, status: 'active' },
        { email: 'jaya@royalenfield.com', fullName: 'Jaya', roleCode: 'DD Lead', zoneId: zoneN.id, password: hashedPassword, status: 'active' },
        { email: 'ganesh@royalenfield.com', fullName: 'ganesh', roleCode: 'DD Head', password: hashedPassword, status: 'active' },
        { email: 'yashwin@royalenfield.com', fullName: 'Yashwin', roleCode: 'NBH', password: hashedPassword, status: 'active' },
        { email: 'fdd@royalenfield.com', fullName: 'FDD Team', roleCode: 'FDD', password: hashedPassword, status: 'active' },
        { email: 'finance@royalenfield.com', fullName: 'Finance Admin', roleCode: 'Finance', password: hashedPassword, status: 'active' },
        { email: 'abhishek@royalenfield.com', fullName: 'abhishek', roleCode: 'ASM', password: hashedPassword, status: 'active' },
        { email: 'lince@royalenfield.com', fullName: 'Lince', roleCode: 'DD Admin', password: hashedPassword, status: 'active' },
        { email: 'legal@royalenfield.com', fullName: 'Legal Admin', roleCode: 'Legal Admin', password: hashedPassword, status: 'active' },
        { email: 'ceo@royalenfield.com', fullName: 'CEO', roleCode: 'CEO', password: hashedPassword, status: 'active' },
        { email: 'cco@royalenfield.com', fullName: 'CCO', roleCode: 'CCO', password: hashedPassword, status: 'active' }
    ];

    for (const u of users) {
        const user = await User.create(u);
        const role = await Role.findOne({ where: { roleCode: u.roleCode } });
        if (role) {
            await UserRole.create({ userId: user.id, roleId: role.id, isActive: true, isPrimary: true });
        }
    }

    // 4. Questionnaire Seed
    await Questionnaire.create({
        title: 'Dealer Onboarding Questionnaire v1',
        version: '1.0',
        description: 'Standard questionnaire for new dealership applications',
        isPublished: true,
        status: 'published'
    });

    console.log('--- Hierarchy Sync ---');
    await syncLocationManagers(sDelhi.id);
    await syncLocationManagers(blr.id);

    console.log('--- DATABASE RESET COMPLETE ---');
}

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