const Branch = require('../models/Branch');
const TransactionDetail = require('../models/TransactionDetail');
const mongoose = require('mongoose');


// Get transaction summary by item and branch
exports.getTransactionSummary = async (req, res) => {
  try {
    // if you want Fetch all branches change use companyId instead of branch ID
    const branchId=req.query.branchId;
   
    const branches = await Branch.find({_id:branchId}, '_id name').lean();

    // Set default date range if not provided
    let startDate = req.query.startDate ? new Date(req.query.startDate) : new Date(); // 
    let endDate = req.query.endDate ? new Date(req.query.endDate) : new Date(); // 
    startDate= new Date(startDate.setUTCHours(0,0,0,0));
    endDate= new Date(endDate.setUTCHours(23, 59, 59, 999));
 
  // Check if branchId is a valid ObjectId
  if (!mongoose.isValidObjectId(branchId)) {
   console.log("invalid")
  }

   
const transactionType=req.query.transactionType?req.query.transactionType:"selling";//  set default type to selling type

    // Aggregate total quantity and price per branch, item, and transaction type
    const summaries = await TransactionDetail.aggregate([
      {
        $match: {  branchId: new mongoose.Types.ObjectId(branchId), //
          createdAt: { $gte: startDate, $lte: endDate },
          // Include only relevant transaction types
          transactionType: transactionType,
       
        }
      },
      {
        $group: {
          _id: {
            itemId: '$itemId',
            branchId: '$branchId',
            transactionType: '$transactionType'
          },
          totalQuantity: { $sum: '$quantity' },
          totalPrice: { $sum: '$total' }
        }
      },
      {
        $lookup: {
          from: 'items',
          localField: '_id.itemId',
          foreignField: '_id',
          as: 'item'
        }
      },
      {
        $unwind: '$item'
      },
      {
        $group: {
          _id: { itemId: '$_id.itemId', branchId: '$_id.branchId' },
          name: { $first: '$item.name' },
          branches: {
            $push: {
              branchId: '$_id.branchId',
              transactionType: '$_id.transactionType',
              totalQuantity: '$totalQuantity',
              totalPrice: '$totalPrice'
            }
          }
        }
      },
      // Sort by item name
  {
    $sort: { name: 1 } // 1 for ascending order, -1 for descending order
  }
    ]);

    // Respond with summaries and branches
    //console.dir(summaries, { depth: null });

    res.json({ summaries, branches });
  } catch (error) {
    console.error('Error fetching transaction summary:', error);
    res.status(500).json({ message: 'Failed to fetch transaction summary' });
  }
};














