const express = require('express');
const db = require('../db/models');
const { wrapAsync } = require('../helpers');
const passport = require('passport');

const router = express.Router();

router.get('/stats', passport.authenticate('jwt', { session: false }), wrapAsync(async (req, res) => {
  const organizationsId = req.currentUser.organizationsId || req.currentUser.organizations?.id;
  const { merchantId, firmId } = req.query;
  
  if (!organizationsId) {
    return res.json({
      revenue: 0,
      expenses: 0,
      profit: 0,
      vatPayable: 0,
      recentTransactions: []
    });
  }

  let where = { organizationsId };
  if (merchantId) {
    where.merchantId = merchantId;
  } else if (firmId) {
    // If firmId is provided, we might want to filter by merchants belonging to that firm
    const merchantsInFirm = await db.merchants.findAll({
      where: { firmId },
      attributes: ['id']
    });
    const merchantIds = merchantsInFirm.map(m => m.id);
    where.merchantId = { [db.Sequelize.Op.in]: merchantIds };
  }

  // Calculate Revenue (Sales Invoices)
  const sales = await db.sales_invoices.findAll({
    where,
  });
  const totalRevenue = sales.reduce((sum, si) => sum + parseFloat(si.total_amount || 0), 0);

  // Calculate Expenses (Purchase Invoices + Expenses table)
  const purchases = await db.purchase_invoices.findAll({
    where,
  });
  const totalPurchases = purchases.reduce((sum, pi) => sum + parseFloat(pi.total_amount || 0), 0);

  const expensesTable = await db.expenses.findAll({
    where,
  });
  const totalExpenses = expensesTable.reduce((sum, e) => sum + parseFloat(e.amount || 0), 0);

  const combinedExpenses = totalPurchases + totalExpenses;

  // Recent Transactions (Limit 5)
  const recentSales = await db.sales_invoices.findAll({
    where,
    include: [{ model: db.customers, as: 'customer' }],
    limit: 5,
    order: [['invoice_date', 'DESC']]
  });

  const recentPurchases = await db.purchase_invoices.findAll({
    where,
    include: [{ model: db.suppliers, as: 'supplier' }],
    limit: 5,
    order: [['invoice_date', 'DESC']]
  });

  const recentExpenses = await db.expenses.findAll({
    where,
    limit: 5,
    order: [['expense_date', 'DESC']]
  });

  let allRecent = [
    ...recentSales.map(si => ({
      date: si.invoice_date,
      description: `Sale - ${si.customer?.name || 'Unknown'}`,
      type: 'Income',
      amount: si.total_amount,
      isIncome: true
    })),
    ...recentPurchases.map(pi => ({
      date: pi.invoice_date,
      description: `Purchase - ${pi.supplier?.name || 'Unknown'}`,
      type: 'Expense',
      amount: pi.total_amount,
      isIncome: false
    })),
    ...recentExpenses.map(e => ({
      date: e.expense_date,
      description: `Expense - ${e.description}`,
      type: 'Expense',
      amount: e.amount,
      isIncome: false
    }))
  ];

  allRecent.sort((a, b) => new Date(b.date) - new Date(a.date));
  const top5Recent = allRecent.slice(0, 5);

  // Profit
  const profit = totalRevenue - combinedExpenses;

  // Simple VAT Payable (15% of Revenue - 15% of Purchases)
  const vatPayable = (totalRevenue * 0.15) - (totalPurchases * 0.15);

  res.json({
    revenue: totalRevenue,
    expenses: combinedExpenses,
    profit: profit,
    vatPayable: vatPayable,
    recentTransactions: top5Recent
  });
}));

module.exports = router;