const { sequelize } = require('./config/db');
const { User, Role } = require('./models/foundation');
const { ExpenseCategory } = require('./models/expense');
const { Budget } = require('./models/budget');
const { Employee, PayrollRun, Payslip } = require('./models/payroll');
const bcrypt = require('bcryptjs');

const seed = async () => {
    try {
        await sequelize.sync({ force: false });

        const [adminRole] = await Role.findOrCreate({ where: { constant: 'SUPER_ADMIN' }, defaults: { name: 'Super Admin' } });
        const [hrRole] = await Role.findOrCreate({ where: { constant: 'HR' }, defaults: { name: 'Human Resources' } });
        const [financeRole] = await Role.findOrCreate({ where: { constant: 'FINANCE' }, defaults: { name: 'Finance Manager' } });

        const adminUser = await User.findOne({ where: { email: 'admin@financepro.com' } });
        const password = await bcrypt.hash('password123', 10);

        // 1. Create HR & Finance Users
        await User.findOrCreate({
            where: { email: 'hr@financepro.com' },
            defaults: { fullName: 'Sarah HR', password, roleId: hrRole.id, isActive: true }
        });

        await User.findOrCreate({
            where: { email: 'cfo@financepro.com' },
            defaults: { fullName: 'Mike CFO', password, roleId: financeRole.id, isActive: true }
        });

        // 2. Create Employees
        const employees = [
            { firstName: 'Alice', lastName: 'Dev', email: 'alice@financepro.com', position: 'Senior Dev', joinDate: '2025-01-10', baseSalary: 6000.00 },
            { firstName: 'Bob', lastName: 'Sales', email: 'bob@financepro.com', position: 'Sales Lead', joinDate: '2025-02-01', baseSalary: 4500.00 },
            { firstName: 'Charlie', lastName: 'Support', email: 'charlie@financepro.com', position: 'Support Agent', joinDate: '2025-03-15', baseSalary: 3200.00 },
        ];

        for (const emp of employees) {
            await Employee.findOrCreate({ where: { email: emp.email }, defaults: emp });
        }

        // 3. Create Budget
        const rentCat = await ExpenseCategory.findOne({ where: { name: 'Rent & Office' } });
        if (rentCat) {
            const period = new Date().toISOString().slice(0, 7); // Current Month
            await Budget.findOrCreate({
                where: { expenseCategoryId: rentCat.id, period },
                defaults: { amount: 3000.00, createdBy: adminUser.id }
            });
        }

        console.log('✅ Phase 6 (New Modules) Seeding Complete');
        process.exit(0);
    } catch (err) {
        console.error('❌ Seeding failed:', err);
        process.exit(1);
    }
};

seed();
