const { sequelize } = require('./config/db');
const { User, Role } = require('./models/foundation');
const { Client } = require('./models/client');
const { Invoice } = require('./models/billing');
const { Payment } = require('./models/payment');
const bcrypt = require('bcryptjs');

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

        // 1. Ensure CLIENT role exists
        const [clientRole] = await Role.findOrCreate({
            where: { constant: 'CLIENT' },
            defaults: { name: 'Client Portal User' }
        });

        // 2. Get a sample client (e.g., Acme Corp from Phase 3)
        const acmeClient = await Client.findOne({ where: { name: 'Acme Corp' } });
        if (!acmeClient) {
            console.error('❌ Acme Corp not found. Please run seed_phase3.js first.');
            process.exit(1);
        }

        // 3. Create Client Portal User
        const hashedPassword = await bcrypt.hash('client123', 10);
        const [clientUser] = await User.findOrCreate({
            where: { email: 'billing@acme.com' },
            defaults: {
                fullName: 'Acme Billing Dept',
                password: hashedPassword,
                isActive: true,
                roleId: clientRole.id,
                clientId: acmeClient.id
            }
        });

        // 4. Seed some payments if they don't exist
        const inv1 = await Invoice.findOne({ where: { clientId: acmeClient.id } });
        if (inv1) {
            const paymentCheck = await Payment.findOne({ where: { invoiceId: inv1.id } });
            if (!paymentCheck) {
                await Payment.create({
                    invoiceId: inv1.id,
                    clientId: acmeClient.id,
                    amount: 500.00,
                    paymentMethod: 'Bank Transfer',
                    transactionReference: 'TRX-112233',
                    status: 'Completed'
                });

                // Update invoice balance manually for seed
                inv1.balanceDue = Number(inv1.balanceDue) - 500.00;
                if (inv1.balanceDue <= 0) inv1.status = 'Paid';
                await inv1.save();
            }
        }

        console.log('✅ Phase 5 Seeding Complete');
        console.log('--- Client Portal Credentials ---');
        console.log('Email: billing@acme.com');
        console.log('Password: client123');
        process.exit(0);
    } catch (err) {
        console.error('❌ Seeding failed:', err);
        process.exit(1);
    }
};

seed();
