const express = require('express');
const router = express.Router();
const Transaction = require('../models/Transaction');
const BranchInventory = require('../models/BranchInventory');
const TransactionDetail = require('../models/TransactionDetail');
const Item = require('../models/Item'); // Import the Item model for stock management
const { getTransactionSummary } = require('../controllers/transactionSummaryController');
const { updateTransactionDetail, createTransaction,getTransaction} = require('../controllers/transactionController');

// Route to fetch transaction summary
router.get('/summary', getTransactionSummary);

router.get('/one', getTransaction);
// PUT: Update a single transaction detail
router.put('/update', updateTransactionDetail);
router.post('/',createTransaction);

module.exports = router;




// // POST: Create a new transaction and transaction details
// router.post('/', async (req, res) => {
//   try {
//     const { companyId, branchId, transactionType, transactionDate, items, customerId, totalItems, subtotal } = req.body;
    
//     // Convert the transactionDate to a Date object
//     const date = new Date(transactionDate);

//     // Step 1: Create a new transaction with custom date
//     const newTransaction = new Transaction({
//       companyId,
//       branchId,
//       customerId,
//       totalItems,
//       subtotal,
//       transactionType,
//       createdAt: date,
//       updatedAt: date
//     });

//     const savedTransaction = await newTransaction.save();

//     // Step 2: Save transaction details with avg_price and custom date
//     const transactionDetailsPromises = items.map(async (item) => {
//       // Find the item's avg_price from the Item collection
//       const foundItem = await Item.findById(item.itemId);
//       if (!foundItem) {
//         throw new Error(`Item with ID ${item.itemId} not found.`);
//       }

//       // Calculate the profit as price - avg_price
//       const profit = item.price - foundItem.avg_price;

      
//       const profitMargin = ((profit / item.price) * 100).toFixed(2); 
     


//       return {
//         transactionId: savedTransaction._id,
//         companyId,
//         branchId,
//         itemId: item.itemId,
//         name: item.name,
//         code: item.code,
//         quantity: item.quantity,
//         balance: item.balance,
//         price: item.price,
//         avg_price: foundItem.avg_price, // Include avg_price
//         profit, // Calculate profit
//         profitMargin ,
//         total: item.total,
//         transactionType: transactionType, // Include transaction type
//         createdAt: date,
//         updatedAt: date
//       };
//     });

//     const transactionDetails = await Promise.all(transactionDetailsPromises);

//     await TransactionDetail.insertMany(transactionDetails);

//     // Step 3: Update branch inventory for each item
//     if (transactionType === 'selling') {
//       for (const item of items) {
//         const branchInventory = await BranchInventory.findOne({ branchId, itemId: item.itemId });
//         if (branchInventory.quantity < item.quantity) {
//           return res.status(400).json({ success: false, message: `Insufficient stock for item ${item.name}` });
//         }
//       }
//     }

//     for (const item of items) {
//       const updateOperation = transactionType === 'selling' ? -item.quantity : item.quantity;

//       const inventoryUpdate = await BranchInventory.findOneAndUpdate(
//         { branchId, itemId: item.itemId },
//         { $inc: { quantity: updateOperation } },
//         { new: true }
//       );

//       if (!inventoryUpdate) {
//         // If inventory doesn't exist, create it for the first time (for purchasing cases)
//         if (transactionType === 'purchasing') {
//           await BranchInventory.create({
//             companyId,
//             branchId,
//             itemId: item.itemId,
//             quantity: item.quantity,
//           });
//         } else {
//           // Return error for insufficient stock in selling case
//           return res.status(400).json({ success: false, message: `Insufficient stock or not branch created for item: ${item.name}` });
//         }
//       }
//     }

//     res.status(201).json({ success: true, message: 'Transaction completed successfully!' });
//   } catch (error) {
//     console.error('Error creating transaction:', error);
//     res.status(500).json({ message: 'Error creating transaction', error });
//   }
// });

