const CashOut = require('../models/CashOut'); // Assuming your updated model file

// Add bulk cash outs
exports.addBulkCashOuts = async (req, res) => {
  try {
    const { cashOuts } = req.body; // Renamed from "expenses"

    console.log(req.body);

    if (!cashOuts || cashOuts.length === 0) {
      return res.status(400).json({ success: false, message: 'No cash outs provided.' });
    }

    // Validate that all cash outs have companyId and branchId
    for (let cashOut of cashOuts) {
      if (!cashOut.companyId || !cashOut.branchId) {
        return res.status(400).json({
          success: false,
          message: 'Each cash out must include companyId and branchId.',
        });
      }
    }

    // Insert all cash outs at once
    const insertedCashOuts = await CashOut.insertMany(cashOuts);

    res.status(201).json({
      success: true,
      message: 'Cash outs added successfully.',
      data: insertedCashOuts,
    });
  } catch (error) {
    console.error('Error adding cash outs:', error);
    res.status(500).json({ success: false, message: 'Error adding cash outs.' });
  }
};

// Get cash outs by date, companyId, and branchId
exports.getCashOutsByDate = async (req, res) => {
  try {
    const { date } = req.params;
    const { companyId, branchId } = req.query;

    if (!companyId || !branchId) {
      return res.status(400).json({
        success: false,
        message: 'Both companyId and branchId are required.',
      });
    }

    const cashOuts = await CashOut.find({ date, companyId, branchId });

    if (!cashOuts || cashOuts.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'No cash outs found for this date, company, and branch.',
      });
    }

    res.status(200).json({
      success: true,
      data: cashOuts,
    });
  } catch (error) {
    console.error('Error fetching cash outs:', error);
    res.status(500).json({ success: false, message: 'Error fetching cash outs.' });
  }
};

// Controller function to delete a cash out by ID
exports.deleteCashOut = async (req, res) => {
  const cashOutId = req.params.id;

  try {
    const cashOut = await CashOut.findById(cashOutId);

    if (!cashOut) {
      return res.status(404).json({ success: false, message: 'Cash out not found' });
    }

    await CashOut.findByIdAndDelete(cashOutId);
    res.status(200).json({ success: true, message: 'Cash out deleted successfully' });
  } catch (error) {
    console.error('Error deleting cash out:', error);
    res.status(500).json({ success: false, message: 'Error deleting cash out' });
  }
};