const { sequelize } = require('./config/db');
const { User, Role } = require('./models/foundation');
const { Income, IncomeCategory } = require('./models/income');
const bcrypt = require('bcryptjs');

const seed = async () => {
    try {
        await sequelize.sync({ force: false }); // Don't wipe everything, just ensure tables exist

        // 1. Roles (if not exist)
        const [superAdminRole] = await Role.findOrCreate({ where: { constant: 'SUPER_ADMIN' }, defaults: { name: 'Super Admin' } });
        await Role.findOrCreate({ where: { constant: 'FINANCE' }, defaults: { name: 'Finance Manager' } });
        await Role.findOrCreate({ where: { constant: 'HR' }, defaults: { name: 'Human Resources' } });

        // 2. Admin User
        const adminPassword = await bcrypt.hash('admin123', 10);
        const [adminUser] = await User.findOrCreate({
            where: { email: 'admin@financepro.com' },
            defaults: {
                fullName: 'System Administrator',
                password: adminPassword,
                roleId: superAdminRole.id,
                isActive: true
            }
        });

        // 3. Income Categories
        const categories = [
            { name: 'Software Development', description: 'Custom software services' },
            { name: 'Consulting', description: 'Business and tech consulting' },
            { name: 'SaaS Subscription', description: 'Monthly recurring revenue' },
            { name: 'CRM Import (Sales)', description: 'Imported from external CRM', isActive: true },
        ];

        for (const cat of categories) {
            await IncomeCategory.findOrCreate({ where: { name: cat.name }, defaults: cat });
        }

        const devCat = await IncomeCategory.findOne({ where: { name: 'Software Development' } });
        const crmCat = await IncomeCategory.findOne({ where: { name: 'CRM Import (Sales)' } });

        // 4. Sample Income
        const incomeData = [
            {
                amount: 5000.00,
                incomeCategoryId: devCat.id,
                source: 'MANUAL',
                reference: 'INV-2026-001',
                receivedDate: '2026-01-20',
                createdBy: adminUser.id,
                notes: 'Initial deposit for project Phoenix'
            },
            {
                amount: 12500.00,
                incomeCategoryId: crmCat.id,
                source: 'CRM',
                reference: 'CRM-TRX-9921',
                receivedDate: '2026-01-25',
                isReadOnly: true,
                notes: 'Monthly bulk import from SalesForce'
            }
        ];

        for (const data of incomeData) {
            const exists = await Income.findOne({ where: { reference: data.reference } });
            if (!exists) await Income.create(data);
        }

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

seed();
