const BankTransaction = require('../models/BankTransaction');
const BankAccount = require('../models/BankAccount');

// Create a new bank transaction
exports.createBankTransaction = async (req, res) => {
  try {
    const { companyId, branchId, bankAccountId, transactionType, amount } = req.body;

    // Step 1: Get the current balance of the bank account
    const bankAccount = await BankAccount.findById(bankAccountId);
    
    if (!bankAccount) {
      return res.status(404).json({ message: 'Bank account not found' });
    }

    let newBalance = bankAccount.balance;

    // Step 2: Update the balance based on transaction type
    if (transactionType === 'deposit') {
      newBalance += amount; // Add amount for deposit
    } else if (transactionType === 'withdrawal') {
      if (amount > newBalance) {
        return res.status(400).json({ message: 'Insufficient balance' });
      }
      newBalance -= amount; // Subtract amount for withdrawal
    } else {
      return res.status(400).json({ message: 'Invalid transaction type' });
    }

    // Step 3: Update the bank account balance
    bankAccount.balance = newBalance;
    await bankAccount.save();

    // Step 4: Create a new bank transaction record
    const newTransaction = new BankTransaction({
      companyId,
      branchId,
      bankAccountId,
      transactionType,
      amount,
      balance: newBalance // Store the updated balance
    });

    const savedTransaction = await newTransaction.save();



//update summary 
// const { runSummarySaving } = require('./autorun.js');
// runSummarySaving();


    // Step 5: Return the saved transaction

 // Return the saved transaction with a success message
 res.status(201).json({
    message: 'Transaction saved successfully!',
    data: savedTransaction
  });


  } catch (error) {
    console.error('Error creating bank transaction:', error);
    res.status(500).json({ message: 'Server error', error: error.message });
  }
};


// Get all bank transactions
// Get all bank transactions
exports.getBankTransactions = async (req, res) => {
    try {
      const companyId = req.query.companyId;  // Get companyId from query parameters
  
      // Ensure companyId is provided
      if (!companyId) {
        return res.status(400).json({ message: 'Company ID is required' });
      }
  
      // Fetch transactions filtered by companyId and populate related fields
      const transactions = await BankTransaction.find({ companyId }).sort({createdAt:-1})
        .populate('companyId')
        .populate('branchId')
        .populate('bankAccountId');
  
      // Send the transactions as a response
      res.status(200).json(transactions);
      console.log("Transactions:", transactions);
    } catch (error) {
      console.error('Error fetching bank transactions:', error);
      res.status(500).json({ message: 'Server error', error });
    }
  };
  

// Get a single bank transaction by ID
exports.getBankTransactionById = async (req, res) => {
  try {
    const transaction = await BankTransaction.findById(req.params.id).populate('companyId branchId bankAccountId');
    if (!transaction) {
      return res.status(404).json({ message: 'Transaction not found' });
    }
    res.status(200).json(transaction);
  } catch (error) {
    console.error('Error fetching bank transaction:', error);
    res.status(500).json({ message: 'Server error' });
  }
};

// Update a bank transaction
exports.updateBankTransaction = async (req, res) => {
  try {
    const updatedTransaction = await BankTransaction.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!updatedTransaction) {
      return res.status(404).json({ message: 'Transaction not found' });
    }
    res.status(200).json(updatedTransaction);
  } catch (error) {
    console.error('Error updating bank transaction:', error);
    res.status(500).json({ message: 'Server error' });
  }
};

// Delete a bank transaction
exports.deleteBankTransaction = async (req, res) => {
  try {
    const deletedTransaction = await BankTransaction.findByIdAndDelete(req.params.id);
    if (!deletedTransaction) {
      return res.status(404).json({ message: 'Transaction not found' });
    }
    res.status(200).json({ message: 'Transaction deleted successfully' });
  } catch (error) {
    console.error('Error deleting bank transaction:', error);
    res.status(500).json({ message: 'Server error' });
  }
};
