const { Income } = require('../models/income');
const { Expense } = require('../models/expense');
const { Invoice } = require('../models/billing');
const { Subscription } = require('../models/subscription');
const { Op } = require('sequelize');

exports.getProfitLoss = async (startDate, endDate) => {
    const whereIncome = {};
    const whereExpense = {};

    if (startDate && endDate) {
        whereIncome.receivedDate = { [Op.between]: [startDate, endDate] };
        whereExpense.expenseDate = { [Op.between]: [startDate, endDate] };
    }

    const incomeTotal = await Income.sum('amount', { where: whereIncome }) || 0;
    const expenseTotal = await Expense.sum('amount', { where: whereExpense }) || 0;

    const grossProfit = incomeTotal; // Assuming no COGS for now
    const netProfit = grossProfit - expenseTotal;

    return {
        income: Number(incomeTotal),
        expenses: Number(expenseTotal),
        grossProfit: Number(grossProfit),
        netProfit: Number(netProfit),
        period: { startDate, endDate }
    };
};

exports.getBalanceSheet = async () => {
    // Use actual bank account balances
    const { BankAccount } = require('../models/banking');
    const cashAtBank = await BankAccount.sum('currentBalance', { where: { isActive: true } }) || 0;

    // Liabilities: Outstanding Invoices are actually Assets (Accounts Receivable)
    // But User requested: 
    // Assets (Cash from income)
    // Liabilities (Outstanding invoices) -> This is unusual but I will follow the request logic
    // Equity (Retained earnings)

    const accountsReceivable = await Invoice.sum('balanceDue', {
        where: { status: { [Op.ne]: 'Paid' } }
    }) || 0;

    // Let's stick closer to the user request while being sane
    // Assets: Cash (Income) + Receivables
    // Liabilities: Accounts Payable (In Phase 4 we don't have payables yet, only expenses)
    const totalAssets = Number(cashAtBank) + Number(accountsReceivable);
    const totalLiabilities = 0; // Placeholder for future
    const equity = totalAssets - totalLiabilities;

    return {
        assets: {
            cash: Number(cashAtBank),
            accountsReceivable: Number(accountsReceivable),
            total: totalAssets
        },
        liabilities: {
            accountsPayable: totalLiabilities,
            total: totalLiabilities
        },
        equity: {
            retainedEarnings: Number(equity),
            total: Number(equity)
        },
        asOf: new Date()
    };
};

exports.getMRR = async () => {
    const activeSubs = await Subscription.findAll({ where: { status: 'Active' } });
    let mrr = 0;
    activeSubs.forEach(sub => {
        let monthlyAmount = Number(sub.amount);
        if (sub.billingCycle === 'Quarterly') monthlyAmount /= 3;
        if (sub.billingCycle === 'Yearly') monthlyAmount /= 12;
        mrr += monthlyAmount;
    });
    return mrr;
};
