
const TransactionDetail = require('../models/TransactionDetail');
const BranchInventory = require('../models/BranchInventory');
const Transfer = require('../models/Transfer');




  // Assuming you have your async handler for the API request
const getCombinedData = async (req, res) => {
    try {
        const itemId = req.params.itemId;
        const branchId = req.query.branchId;
        const companyId = req.query.companyId;
  
      // Set default dates 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));
   
      // Step 1: Fetch Transaction Details
  
      let transactionType = req.query.transactionType ? req.query.transactionType : 'selling'; // Default to selling
  
      // Prepare filter for transactionType
      let transactionTypeFilter;
      if (transactionType === 'All') {
        transactionTypeFilter = { $in: ['producing','using','selling', 'purchasing','ordering','transfering'] };
      } else {
        transactionTypeFilter = transactionType;
      }
  
      // Fetch transaction details for the specified item and dates
      const transactionDetails = await TransactionDetail.find({
        itemId: itemId,
       createdAt: { $gte: startDate, $lte: endDate },
        transactionType: transactionTypeFilter,
      })
        .populate([
          {
            path: 'transactionId', // Populates the transactionId field
            populate: {
              path: 'customerId', // Nested populate for customerId within transactionId
              model: 'Customer', // Specify the model to be populated
            },
          },
          {
            path: 'itemId', // Populates the itemId field
            model: 'Item', // Specify the model to be populated for itemId
          },
        ])
        .sort({ createdAt: -1 }) // Sort transaction details by createdAt (descending)
        .lean(); // Convert to plain objects for easier manipulation
  

      
      // Step 2: Fetch Transfer Data
      const transfers = await Transfer.find({ 
         itemId: itemId,
         createdAt: { $gte: startDate, $lte: endDate },
        $or: [{ fromBranch: branchId }, { toBranch: branchId }],
      })
        .populate('fromBranch toBranch itemId', 'name')
        .lean(); // Convert to plain objects for easier manipulation
  
      // Add transfer type based on the branch
      const formattedTransfers = transfers.map((transfer) => {
        const transferType = transfer.fromBranch._id.toString() === branchId ? 'Out' : 'In';
        return {
          ...transfer,
          transferType,
        };
      });
  
      // Step 3: Merge and Add Type
      const combinedResult = [
        ...transactionDetails.map((detail) => ({
          ...detail,
          type: 'transaction', // Add type to distinguish between transaction and transfer
        })),
        ...formattedTransfers.map((transfer) => ({
          ...transfer,
          type: 'transfer', // Add type to distinguish between transaction and transfer
        })),
      ];
  
      // Step 4: Sort by createdAt (descending)
      combinedResult.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
  
      // Step 5: Fetch branch inventory for the specified item and branch
      const inventory = await BranchInventory.findOne({ itemId: itemId, branchId: branchId });
 
      // Step 6: Return the combined and sorted data along with inventory
      res.status(200).json({ details: combinedResult, inventory });
    } catch (error) {
      console.error('Error fetching combined data:', error);
      res.status(500).json({ message: 'Error fetching combined data' });
    }
  };
  



// Controller function to fetch details for a specific item
const getItemDetails= async (req, res) => {
    try {
        const itemId = req.params.itemId;
        const branchId = req.query.branchId;
        const companyId = req.query.companyId;
        
       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));
    


        let transactionType = req.query.transactionType ? req.query.transactionType : "selling"; // Default to selling

        // Prepare filter for transactionType
        let transactionTypeFilter;
        if (transactionType === 'All') {
            transactionTypeFilter = { $in: ['selling', 'purchasing'] };
        } else {
            transactionTypeFilter = transactionType;
        }
        








        
        // Find transaction details for the specified item and dates
        const details = await TransactionDetail.find({
            itemId: itemId,
            createdAt: { $gte: startDate, $lte: endDate },
            transactionType: transactionTypeFilter  // Correctly apply the filter
        })     
        .populate([
            {
                path: 'transactionId', // Populates the itemId field
                populate: {
                    path: 'customerId', // Nested populate for customerId within itemId
                    model: 'Customer' // Specify the model to be populated
                }
            },
            {
                path: 'itemId', // Populates the transactionId field
                model: 'Transaction' // Specify the model to be populated for transactionId
            }
        ])
        .sort({ createdAt: -1 }); // Sort descending
        


 
        // Find branch inventory for the specified item and branch
        const inventory = await BranchInventory.findOne({ itemId: itemId, branchId: branchId });

        res.json({ details, inventory });
    } catch (error) {
        console.error('Error fetching item details:', error);
        res.status(500).json({ message: 'Error fetching item details', error });
    }
};

module.exports = { getItemDetails,getCombinedData };




