const { sequelize } = require('./config/db');
const { User } = require('./models/foundation');
const { Client } = require('./models/client');
const { Subscription, SubscriptionItem } = require('./models/subscription');

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

        // 1. Get Admin User
        const adminUser = await User.findOne({ where: { email: 'admin@financepro.com' } });
        const acmeClient = await Client.findOne({ where: { name: 'Acme Corp' } });
        const globexClient = await Client.findOne({ where: { name: 'Globex Corp' } });

        if (!adminUser || !acmeClient || !globexClient) {
            console.error('❌ Required data from previous phases missing. Run 1-3 first.');
            process.exit(1);
        }

        // 2. Sample Subscriptions
        const sub1 = await Subscription.create({
            clientId: acmeClient.id,
            name: 'Enterprise Maintenance (Monthly)',
            billingCycle: 'Monthly',
            startDate: '2026-01-01',
            nextBillingDate: '2026-01-26', // Set to today to test scheduler
            amount: 1500.00,
            status: 'Active',
            autoSendInvoice: true,
            createdBy: adminUser.id
        });

        await SubscriptionItem.create({
            subscriptionId: sub1.id,
            description: 'Monthly Cloud Infrastructure Support',
            quantity: 1,
            unitPrice: 1500.00,
            lineTotal: 1500.00
        });

        const sub2 = await Subscription.create({
            clientId: globexClient.id,
            name: 'Tier 3 Support Package',
            billingCycle: 'Yearly',
            startDate: '2026-01-10',
            nextBillingDate: '2027-01-10',
            amount: 12000.00,
            status: 'Active',
            autoSendInvoice: true,
            createdBy: adminUser.id
        });

        await SubscriptionItem.create({
            subscriptionId: sub2.id,
            description: 'Annual Dedicated Technical Support',
            quantity: 1,
            unitPrice: 12000.00,
            lineTotal: 12000.00
        });

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

seed();
