import 'dotenv/config';
import db from '../src/database/models/index.js';
import bcrypt from 'bcryptjs';
import { ROLES } from '../src/common/config/constants.js';
import { resolveManagerCode } from '../src/services/userRoleCode.service.js';

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

async function masterReset() {
    console.log('--- RELOADING DATABASE FOR OFFBOARDING TEST ---');

    try {
        await db.sequelize.authenticate();
        
        // 1. Force Sync (Drop and Recreate)
        await db.sequelize.sync({ force: true });
        console.log('✅ Schema reset complete.');

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

        // 2. Seed All Roles
        const rolesToSeed = Object.values(ROLES).map(code => ({
            roleCode: code,
            roleName: code,
            category: 'SYSTEM'
        }));

        for (const r of rolesToSeed) {
            await Role.create(r);
        }
        console.log('✅ Roles seeded.');

        // 3. Seed Basic Hierarchy
        const { District } = db;
        const zone = await Zone.create({ name: 'North', code: 'N' });
        const state = await State.create({ name: 'Delhi', zoneId: zone.id });
        const region = await Region.create({ name: 'NCR', zoneId: zone.id });
        
        // Create South Delhi District and link to NCR Region
        const district = await District.create({ 
            name: 'South Delhi', 
            stateId: state.id, 
            regionId: region.id, 
            zoneId: zone.id,
            isActive: true 
        });

        const loc = await Location.create({ 
            name: 'Central Delhi', 
            stateId: state.id, 
            regionId: region.id, 
            zoneId: zone.id,
            districtId: district.id 
        });
        console.log('✅ Hierarchy seeded with South Delhi District.');

        // 4. Seed Essential Users
        const users = [
            { email: 'admin@royalenfield.com', fullName: 'Super Admin', roleCode: ROLES.SUPER_ADMIN },
            { email: 'piyush@royalenfield.com', fullName: 'piyush', roleCode: ROLES.DD_ZM },
            { email: 'manish@royalenfield.com', fullName: 'manish', roleCode: ROLES.RBM },
            { email: 'manav@royalenfield.com', fullName: 'manav', roleCode: ROLES.ZBH },
            { email: 'jaya@royalenfield.com', fullName: 'Jaya', roleCode: ROLES.DD_LEAD },
            { email: 'ganesh@royalenfield.com', fullName: 'ganesh', roleCode: ROLES.DD_HEAD },
            { email: 'yashwin@royalenfield.com', fullName: 'Yashwin', roleCode: ROLES.NBH },
            { email: 'fdd@royalenfield.com', fullName: 'FDD Team', roleCode: ROLES.FDD },
            { email: 'finance@royalenfield.com', fullName: 'Finance Admin', roleCode: ROLES.FINANCE },
            { email: 'abhishek@royalenfield.com', fullName: 'abhishek', roleCode: ROLES.ASM },
            { email: 'lince@royalenfield.com', fullName: 'Lince', roleCode: ROLES.DD_ADMIN },
            { email: 'legal@royalenfield.com', fullName: 'Legal Admin', roleCode: ROLES.LEGAL_ADMIN },
            { email: 'ceo@royalenfield.com', fullName: 'CEO', roleCode: ROLES.CEO },
            { email: 'cco@royalenfield.com', fullName: 'CCO', roleCode: ROLES.CCO },
        ];

        for (const u of users) {
            const user = await User.create({
                ...u,
                password: hashedPassword,
                status: 'active'
            });
            const role = await Role.findOne({ where: { roleCode: u.roleCode } });
            if (role) {
                // Map assignments based on role category (Regional vs Granular)
                const isRegionalRole = [ROLES.RBM, ROLES.DD_ZM, ROLES.ZBH].includes(u.roleCode as any);
                const isGranularRole = [ROLES.ASM].includes(u.roleCode as any);
                const managerCode = await resolveManagerCode(role.id, u.roleCode as string, null);

                await UserRole.create({
                    userId: user.id,
                    roleId: role.id,
                    isActive: true,
                    isPrimary: true,
                    zoneId: isRegionalRole || isGranularRole ? zone.id : null,
                    regionId: isRegionalRole ? region.id : null,
                    districtId: isGranularRole ? district.id : null,
                    managerCode
                });
            }
        }
        console.log('✅ Standard Users seeded.');

        console.log('ℹ️ Dealer user/profile not auto-seeded in stable reset (as requested).');

        console.log('--- SYSTEM READY FOR OFFBOARDING TESTING ---');
        process.exit(0);
    } catch (error) {
        console.error('❌ Reset failed:', error);
        process.exit(1);
    }
}

masterReset();
