import Product from '../models/Product.js';
import Warehouse from '../models/Warehouse.js';
import StockTransaction from '../models/StockTransaction.js';

const getDailyReport = async (req, res) => {
  try {
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const tomorrow = new Date(today);
    tomorrow.setHours(23, 59, 59, 999);

    const [availableStock, stockInTransactions, stockOutTransactions, totalProducts, totalWarehouses, totalTransactions] = await Promise.all([
      Product.find({}).select('quantityInStock'),
      StockTransaction.find({
        transactionDate: { $gte: today, $lte: tomorrow },
        transactionType: 'Stock In',
      }),
      StockTransaction.find({
        transactionDate: { $gte: today, $lte: tomorrow },
        transactionType: 'Stock Out',
      }),
      Product.countDocuments({}),
      Warehouse.countDocuments({}),
      StockTransaction.countDocuments({}),
    ]);

    const totalStock = availableStock.reduce((sum, p) => sum + p.quantityInStock, 0);
    const totalStockIn = stockInTransactions.reduce((sum, t) => sum + t.quantityMoved, 0);
    const totalStockOut = stockOutTransactions.reduce((sum, t) => sum + t.quantityMoved, 0);

    res.json({
      reportType: 'Daily Report',
      date: today.toISOString().split('T')[0],
      availableStock: totalStock,
      stockInTransactions: stockInTransactions.length,
      stockOutTransactions: stockOutTransactions.length,
      totalProducts,
      totalWarehouses,
      totalTransactions,
      transactions: {
        stockIn: stockInTransactions,
        stockOut: stockOutTransactions,
      },
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

const getWeeklyReport = async (req, res) => {
  try {
    const today = new Date();
    const startOfWeek = new Date(today);
    startOfWeek.setDate(today.getDate() - today.getDay());
    startOfWeek.setHours(0, 0, 0, 0);

    const endOfWeek = new Date(startOfWeek);
    endOfWeek.setDate(startOfWeek.getDate() + 6);
    endOfWeek.setHours(23, 59, 59, 999);

    const [availableStock, stockInTransactions, stockOutTransactions, totalProducts, totalWarehouses, totalTransactions] = await Promise.all([
      Product.find({}).select('quantityInStock'),
      StockTransaction.find({
        transactionDate: { $gte: startOfWeek, $lte: endOfWeek },
        transactionType: 'Stock In',
      }),
      StockTransaction.find({
        transactionDate: { $gte: startOfWeek, $lte: endOfWeek },
        transactionType: 'Stock Out',
      }),
      Product.countDocuments({}),
      Warehouse.countDocuments({}),
      StockTransaction.countDocuments({}),
    ]);

    const totalStock = availableStock.reduce((sum, p) => sum + p.quantityInStock, 0);
    const totalStockIn = stockInTransactions.reduce((sum, t) => sum + t.quantityMoved, 0);
    const totalStockOut = stockOutTransactions.reduce((sum, t) => sum + t.quantityMoved, 0);

    res.json({
      reportType: 'Weekly Report',
      startDate: startOfWeek.toISOString().split('T')[0],
      endDate: endOfWeek.toISOString().split('T')[0],
      availableStock: totalStock,
      stockInTransactions: stockInTransactions.length,
      stockOutTransactions: stockOutTransactions.length,
      totalProducts,
      totalWarehouses,
      totalTransactions,
      transactions: {
        stockIn: stockInTransactions,
        stockOut: stockOutTransactions,
      },
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

const getMonthlyReport = async (req, res) => {
  try {
    const today = new Date();
    const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
    startOfMonth.setHours(0, 0, 0, 0);

    const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    endOfMonth.setHours(23, 59, 59, 999);

    const [availableStock, stockInTransactions, stockOutTransactions, totalProducts, totalWarehouses, totalTransactions] = await Promise.all([
      Product.find({}).select('quantityInStock'),
      StockTransaction.find({
        transactionDate: { $gte: startOfMonth, $lte: endOfMonth },
        transactionType: 'Stock In',
      }),
      StockTransaction.find({
        transactionDate: { $gte: startOfMonth, $lte: endOfMonth },
        transactionType: 'Stock Out',
      }),
      Product.countDocuments({}),
      Warehouse.countDocuments({}),
      StockTransaction.countDocuments({}),
    ]);

    const totalStock = availableStock.reduce((sum, p) => sum + p.quantityInStock, 0);
    const totalStockIn = stockInTransactions.reduce((sum, t) => sum + t.quantityMoved, 0);
    const totalStockOut = stockOutTransactions.reduce((sum, t) => sum + t.quantityMoved, 0);

    res.json({
      reportType: 'Monthly Report',
      startDate: startOfMonth.toISOString().split('T')[0],
      endDate: endOfMonth.toISOString().split('T')[0],
      availableStock: totalStock,
      stockInTransactions: stockInTransactions.length,
      stockOutTransactions: stockOutTransactions.length,
      totalProducts,
      totalWarehouses,
      totalTransactions,
      transactions: {
        stockIn: stockInTransactions,
        stockOut: stockOutTransactions,
      },
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

export { getDailyReport, getWeeklyReport, getMonthlyReport };
