const Expense = require('../models/Expense');

// Add bulk expenses
exports.addBulkExpenses = async (req, res) => {
    try {
        const { expenses } = req.body;

        console.log(req.body)

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

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

        // Insert all expenses at once
        const insertedExpenses = await Expense.insertMany(expenses);
 //update summary 
//  const { runSummarySaving } = require('./autorun.js');
//  runSummarySaving();
 
        res.status(201).json({
            success: true,
            message: 'Expenses added successfully.',
            data: insertedExpenses
        });
    } catch (error) {
        console.error('Error adding expenses:', error);
        res.status(500).json({ success: false, message: 'Error adding expenses.' });
    }
};

// Get expenses by date, companyId, and branchId
exports.getExpensesByDate = async (req, res) => {
    try {
      
        const { companyId, branchId ,startDate,endDate} = req.query;

         console.log(req.query);

        let start = new Date(startDate)|| new Date();
        let end = new Date(endDate)|| new Date();
      
        // Set start to UTC midnight and end to the end of the day in UTC
        start.setUTCHours(0, 0, 0, 0);
        end.setUTCHours(23, 59, 59, 999);
      
        // Query the expenses with the specified filters
        const expenses = await Expense.find({
          companyId,
          branchId,
         date: { $gte: start, $lte: end }, // Date filter
        }).sort({date:-1});


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

        res.status(200).json({
            success: true,
            data: expenses
        });
    } catch (error) {
        console.error('Error fetching expenses:', error);
        res.status(500).json({ success: false, message: 'Error fetching expenses.' });
    }
};
// Controller function to delete an expense by ID
exports.deleteExpense = async (req, res) => {
    const expenseId = req.params.id;
  
    try {
      const expense = await Expense.findById(expenseId);
  
      if (!expense) {
        return res.status(404).json({ success: false, message: 'Expense not found' });
      }
  
      await Expense.findByIdAndDelete(expenseId);
      res.status(200).json({ success: true, message: 'Expense deleted successfully' });
    } catch (error) {
      console.error('Error deleting expense:', error);
      res.status(500).json({ success: false, message: 'Error deleting expense' });
    }
  }