const express = require('express');
const db = require('../db/models');
const { wrapAsync } = require('../helpers');
const { checkCrudPermissions } = require('../middlewares/check-permissions');
const passport = require('passport');

const router = express.Router();

router.get('/', passport.authenticate('jwt', { session: false }), checkCrudPermissions('transactions'), wrapAsync(async (req, res) => {
  const organizationsId = req.currentUser.organizationsId || req.currentUser.organizations?.id;
  
  if (!organizationsId) {
    return res.json({ rows: [], count: 0 });
  }

  const { page = 0, limit = 10, sort = 'desc' } = req.query;

  const offset = parseInt(page) * parseInt(limit);
  const limitInt = parseInt(limit);

  // Fetch from Sales Invoices
  const salesInvoices = await db.sales_invoices.findAll({
    where: { organizationsId },
    include: [{ model: db.customers, as: 'customer' }],
  });

  // Fetch from Purchase Invoices
  const purchaseInvoices = await db.purchase_invoices.findAll({
    where: { organizationsId },
    include: [{ model: db.suppliers, as: 'supplier' }],
  });

  // Fetch from Expenses
  const expenses = await db.expenses.findAll({
    where: { organizationsId },
  });

  // Combine and format
  let transactions = [
    ...salesInvoices.map(si => ({
      id: `sale-${si.id}`,
      originalId: si.id,
      date: si.invoice_date,
      description: `Sale - ${si.customer?.name || 'Unknown Customer'}`,
      type: 'Income',
      amount: si.total_amount,
      isIncome: true,
      status: si.status,
      entity: 'sales_invoices'
    })),
    ...purchaseInvoices.map(pi => ({
      id: `purchase-${pi.id}`,
      originalId: pi.id,
      date: pi.invoice_date,
      description: `Purchase - ${pi.supplier?.name || 'Unknown Supplier'}`,
      type: 'Expense',
      amount: pi.total_amount,
      isIncome: false,
      status: pi.status,
      entity: 'purchase_invoices'
    })),
    ...expenses.map(e => ({
      id: `expense-${e.id}`,
      originalId: e.id,
      date: e.expense_date,
      description: `Expense - ${e.description}`,
      type: 'Expense',
      amount: e.amount,
      isIncome: false,
      status: e.status,
      entity: 'expenses'
    }))
  ];

  // Sort
  transactions.sort((a, b) => {
    const dateA = new Date(a.date);
    const dateB = new Date(b.date);
    if (isNaN(dateA.getTime()) || isNaN(dateB.getTime())) return 0;
    return sort === 'desc' ? dateB.getTime() - dateA.getTime() : dateA.getTime() - dateB.getTime();
  });

  const count = transactions.length;
  const paginatedTransactions = transactions.slice(offset, offset + limitInt);

  res.json({
    rows: paginatedTransactions,
    count
  });
}));

module.exports = router;
