const { Invoice, Quote } = require('../models/billing');
const { Payment } = require('../models/payment');
const { Subscription } = require('../models/subscription');
const { Op } = require('sequelize');

exports.getClientDashboard = async (clientId) => {
    const invoices = await Invoice.findAll({ where: { clientId } });
    const outstanding = invoices
        .filter(i => i.status !== 'Paid' && i.status !== 'Cancelled')
        .reduce((sum, i) => sum + Number(i.balanceDue), 0);

    const payments = await Payment.findAll({
        where: { clientId },
        limit: 5,
        order: [['paymentDate', 'DESC']],
        include: [{ model: Invoice, attributes: ['invoiceNumber'] }]
    });

    const upcomingInvoices = await Subscription.findAll({
        where: { clientId, status: 'Active' },
        attributes: ['name', 'nextBillingDate', 'amount']
    });

    return {
        metrics: {
            outstandingBalance: outstanding,
            totalInvoices: invoices.length,
            paidInvoices: invoices.filter(i => i.status === 'Paid').length
        },
        recentPayments: payments,
        upcomingBilling: upcomingInvoices
    };
};

exports.getClientInvoices = async (clientId) => {
    return await Invoice.findAll({
        where: { clientId },
        order: [['issueDate', 'DESC']]
    });
};

exports.getClientQuotes = async (clientId) => {
    return await Quote.findAll({
        where: { clientId },
        order: [['issueDate', 'DESC']]
    });
};
