const transactionModel = require('../models/bankTransactionModel');

exports.getAccountsSummary = async (req, res) => {
  try {
    const { start_date, end_date } = req.query;

    if (!start_date || !end_date) {
      return res.status(400).json({ error: 'start_date and end_date are required' });
    }

    const data = await transactionModel.getAccountSummaryByDateRange(start_date, end_date);
    res.json(data);
  } catch (err) {
    console.error('Accounts summary error:', err);
    res.status(500).json({ error: err.message });
  }
};


exports.createTransaction = async (req, res) => {
  try {
    await transactionModel.createTransaction(req.body);
    res.json({ message: 'Transaction recorded successfully' });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

exports.getTransactions = async (req, res) => {
  try {
    const { bank_id, start_date, end_date, type } = req.query; // use query params
    const transactions = await transactionModel.getFilteredTransactions(bank_id, start_date, end_date, type);
    res.json(transactions);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: err.message });
  }
};

exports.getTransactionDetails = async (req, res) => {
  try {
    const { id } = req.params;
    const transaction = await transactionModel.getTransactionById(id);

    if (!transaction) {
      return res.status(404).json({ message: 'Transaction not found' });
    }

    let details = null;

    if (transaction.reference_type === 'sale') {
      details = await transactionModel.getSaleDetails(transaction.reference_id);
    } else if (transaction.reference_type === 'purchase') {
      details = await transactionModel.getPurchaseDetails(transaction.reference_id);
    } else if (transaction.reference_type === 'transfer') {
      details = await transactionModel.getTransferDetails(transaction.reference_id);
    }

    res.json({ transaction, details });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: err.message });
  }
};
exports.getTransferReversalHistory = async (req, res) => {
  try {
    const transferId = req.params.id;
    const result = await transactionModel.getReversalHistoryByTransferId(transferId);
    res.json(result);
  } catch (err) {
    console.error('Reversal history fetch failed:', err);
    res.status(500).json({ error: err.message });
  }
};