const Product = require("../models/Product");
const StockTransaction = require("../models/StockTransaction");

const getDateRange = (period) => {
  const now = new Date();
  const start = new Date(now);

  if (period === "weekly") {
    start.setDate(now.getDate() - 7);
  } else if (period === "monthly") {
    start.setMonth(now.getMonth() - 1);
  } else {
    start.setHours(0, 0, 0, 0);
  }

  const end = new Date(now);
  end.setHours(23, 59, 59, 999);

  return { start, end };
};

const getReports = async (req, res) => {
  try {
    const period = req.query.period || "daily";
    const { start, end } = getDateRange(period);

    const availableStock = await Product.find().sort({ productName: 1 });
    const transactions = await StockTransaction.find({
      transactionDate: { $gte: start, $lte: end }
    })
      .populate("product warehouse")
      .sort({ transactionDate: -1 });

    const stockIn = transactions.filter((item) => item.transactionType === "Stock In");
    const stockOut = transactions.filter((item) => item.transactionType === "Stock Out");

    res.json({
      period,
      startDate: start,
      endDate: end,
      availableStock,
      stockIn,
      stockOut
    });
  } catch (error) {
    res.status(500).json({ message: "Reports could not be generated", error: error.message });
  }
};

module.exports = {
  getReports
};
