const { sequelize } = require('./config/db');
const { User } = require('./models/foundation');
const { Client } = require('./models/client');
const { Quote, QuoteItem, Invoice, InvoiceItem } = require('./models/billing');

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

        // 1. Get Admin User
        const adminUser = await User.findOne({ where: { email: 'admin@financepro.com' } });
        if (!adminUser) {
            console.error('❌ Admin user not found. Run Phase 1 first.');
            process.exit(1);
        }

        // 2. Sample Clients
        const clients = [
            { name: 'Acme Corp', email: 'billing@acme.com', phone: '+1555000111', billingAddress: '101 Industrial Ave, NY, 10001' },
            { name: 'Globex Corp', email: 'finance@globex.com', phone: '+1555999000', billingAddress: '742 Evergreen Terrace, Springfield' },
            { name: 'Initech', email: 'peter@initech.com', phone: '+1555123456', billingAddress: 'Floor 4, Unit 201, Silicon Valley, CA' },
        ];

        const seededClients = [];
        for (const c of clients) {
            const [client] = await Client.findOrCreate({ where: { email: c.email }, defaults: c });
            seededClients.push(client);
        }

        // 3. Sample Quotes
        const [q1] = await Quote.findOrCreate({
            where: { quoteNumber: 'QUO-0001' },
            defaults: {
                clientId: seededClients[0].id,
                quoteNumber: 'QUO-0001',
                status: 'Sent',
                issueDate: '2026-01-10',
                expiryDate: '2026-02-10',
                subtotal: 5000.00,
                tax: 0,
                total: 5000.00,
                createdBy: adminUser.id
            }
        });

        await QuoteItem.create({ quoteId: q1.id, description: 'Enterprise Software License', quantity: 1, unitPrice: 5000.00, lineTotal: 5000.00 });

        const [q2] = await Quote.findOrCreate({
            where: { quoteNumber: 'QUO-0002' },
            defaults: {
                clientId: seededClients[1].id,
                quoteNumber: 'QUO-0002',
                status: 'Accepted',
                issueDate: '2026-01-15',
                expiryDate: '2026-02-15',
                subtotal: 2400.00,
                tax: 0,
                total: 2400.00,
                createdBy: adminUser.id
            }
        });

        await QuoteItem.create({ quoteId: q2.id, description: 'Maintenance Services (Monthly)', quantity: 2, unitPrice: 1200.00, lineTotal: 2400.00 });

        // 4. Sample Invoices
        const [inv1] = await Invoice.findOrCreate({
            where: { invoiceNumber: 'INV-0001' },
            defaults: {
                clientId: seededClients[0].id,
                invoiceNumber: 'INV-0001',
                status: 'Paid',
                issueDate: '2026-01-01',
                dueDate: '2026-01-15',
                subtotal: 1000.00,
                tax: 0,
                total: 1000.00,
                balanceDue: 0,
                createdBy: adminUser.id
            }
        });
        await InvoiceItem.create({ invoiceId: inv1.id, description: 'Initial Setup Fee', quantity: 1, unitPrice: 1000.00, lineTotal: 1000.00 });

        const [inv2] = await Invoice.findOrCreate({
            where: { invoiceNumber: 'INV-0002' },
            defaults: {
                clientId: seededClients[2].id,
                invoiceNumber: 'INV-0002',
                status: 'Overdue',
                issueDate: '2025-12-15',
                dueDate: '2025-12-30',
                subtotal: 3500.00,
                tax: 0,
                total: 3500.00,
                balanceDue: 3500.00,
                createdBy: adminUser.id
            }
        });
        await InvoiceItem.create({ invoiceId: inv2.id, description: 'Consultancy Retainer', quantity: 1, unitPrice: 3500.00, lineTotal: 3500.00 });

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

seed();
