const express = require('express');
const router = express.Router();
const { protect, authorize } = require('../middlewares/auth');
const { Income } = require('../models/income');
const { Expense } = require('../models/expense');
const { Invoice } = require('../models/billing');
const { Subscription } = require('../models/subscription');
const { getMRR } = require('../services/reportService');

// All dashboard routes are protected
router.use(protect);

router.get('/metrics', authorize('VIEW_FINANCIALS'), async (req, res) => {
    try {
        const incomeTotal = await Income.sum('amount') || 0;
        const expenseTotal = await Expense.sum('amount') || 0;

        // Use actual bank balance
        const { BankAccount } = require('../models/banking');
        const bankBalance = await BankAccount.sum('currentBalance', { where: { isActive: true } }) || 0;

        const netProfit = incomeTotal - expenseTotal;

        const outstandingInvoices = await Invoice.sum('balanceDue', {
            where: { status: ['Draft', 'Sent'] }
        }) || 0;

        const overdueInvoices = await Invoice.count({
            where: {
                status: ['Draft', 'Sent'],
                dueDate: { [require('sequelize').Op.lt]: new Date() }
            }
        }) || 0;

        const mrr = await getMRR();
        const subscriptionCount = await Subscription.count({ where: { status: 'Active' } }) || 0;

        res.json({
            incomeTotal: Number(incomeTotal),
            expenseTotal: Number(expenseTotal),
            netProfit: Number(netProfit),
            bankBalance: Number(bankBalance),
            billing: {
                outstanding: Number(outstandingInvoices),
                overdue: overdueInvoices
            },
            metrics: {
                mrr: Number(mrr),
                subscriptionCount
            }
        });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

module.exports = router;
