const StockTransaction = require('../models/StockTransaction');
const Product = require('../models/product');

function startOfPeriod(date, period) {
  const value = new Date(date);
  if (period === 'day') {
    value.setHours(0, 0, 0, 0);
  }
  if (period === 'week') {
    const day = value.getDay();
    const diff = value.getDate() - day + (day === 0 ? -6 : 1);
    value.setDate(diff);
    value.setHours(0, 0, 0, 0);
  }
  if (period === 'month') {
    value.setDate(1);
    value.setHours(0, 0, 0, 0);
  }
  return value;
}

exports.getReports = async (req, res) => {
  try {
    const transactions = await StockTransaction.find().populate('product');
    const products = await Product.find();

    const now = new Date();
    const periods = ['day', 'week', 'month'];
    const totals = {};

    periods.forEach((period) => {
      const start = startOfPeriod(now, period);
      totals[period] = {
        stockIn: 0,
        stockOut: 0,
        transactions: 0,
      };
      transactions.forEach((transaction) => {
        if (new Date(transaction.transactionDate) >= start) {
          totals[period].transactions += 1;
          if (transaction.transactionType === 'Stock In') {
            totals[period].stockIn += transaction.quantityMoved;
          } else {
            totals[period].stockOut += transaction.quantityMoved;
          }
        }
      });
    });

    const availableStock = products.map((product) => ({
      productCode: product.productCode,
      productName: product.productName,
      category: product.category,
      quantityInStock: product.quantityInStock,
      supplierName: product.supplierName,
      dateReceived: product.dateReceived,
    }));

    res.json({ totals, availableStock });
  } catch (error) {
    res.status(500).json({ msg: 'Failed to generate reports', error: error.message });
  }
};
