const bankModel = require('../models/bankModel');
const db = require('../db/config');

exports.createBank = async (req, res) => {
  await bankModel.createBank(req.body);
  res.json({ message: 'Bank account created successfully' });
};

exports.getBanks = async (req, res) => {
  const banks = await bankModel.getAllBanks();
  res.json(banks);
};

exports.getBank = async (req, res) => {
  try {
    const bank = await bankModel.getBankById(req.params.id);

    if (!bank) {
      return res.status(404).json({ error: 'Bank not found.' });
    }

    res.json(bank);
  } catch (err) {
    console.error('Get Bank Error:', err);
    res.status(500).json({ error: 'Failed to fetch bank details.' });
  }
};

exports.updateBank = async (req, res) => {
  await bankModel.updateBank(req.params.id, req.body);
  res.json({ message: 'Bank updated successfully' });
};

exports.deleteBank = async (req, res) => {
  try {
    await bankModel.deleteBank(req.params.id);
    res.json({ message: 'Bank soft-deleted successfully' });
  } catch (err) {
    console.error('Delete Bank Error:', err);
    res.status(500).json({ error: 'Failed to delete bank.' });
  }
};

exports.transferBetweenBanks = async (req, res) => {
  const { from_bank_id, to_bank_id, amount, description } = req.body;

  if (from_bank_id === to_bank_id) {
    return res.status(400).json({ error: 'Cannot transfer to the same bank' });
  }

  const conn = await db.getConnection();
  await conn.beginTransaction();

  try {
    const [[fromBank]] = await conn.query('SELECT balance FROM banks WHERE id = ?', [from_bank_id]);
    if (!fromBank || fromBank.balance < amount) {
      await conn.rollback();
      return res.status(400).json({ error: 'Insufficient funds in source bank' });
    }

    // await conn.query('UPDATE banks SET balance = balance - ? WHERE id = ?', [amount, from_bank_id]);
    // await conn.query('UPDATE banks SET balance = balance + ? WHERE id = ?', [amount, to_bank_id]);

    await conn.query(
      'INSERT INTO bank_transactions (bank_id, type, amount, description, related_bank_id, reference_type) VALUES (?, ?, ?, ?, ?, ?)',
      [from_bank_id, 'transfer', amount, `Transfer to bank #${to_bank_id}`, to_bank_id, 'transfer']
    );

    await conn.query(
      'INSERT INTO bank_transactions (bank_id, type, amount, description, related_bank_id, reference_type) VALUES (?, ?, ?, ?, ?, ?)',
      [to_bank_id, 'transfer', amount, `Transfer from bank #${from_bank_id}`, from_bank_id, 'transfer']
    );

    await conn.commit();
    res.json({ success: true });
  } catch (err) {
    await conn.rollback();
    console.error(err);
    res.status(500).json({ error: err.message });
  } finally {
    conn.release();
  }
};

exports.getTransferLogs = async (req, res) => {
  try {
    const [rows] = await bankModel.getBankTransfers();
    res.json(rows);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: err.message });
  }
};

exports.reverseTransfer = async (req, res) => {
  const conn = await db.getConnection();
  await conn.beginTransaction();
  try {
    await bankModel.reverseBankTransfer(req.params.id, conn);
    await conn.commit();
    res.json({ success: true });
  } catch (err) {
    await conn.rollback();
    console.error(err);
    res.status(500).json({ error: err.message });
  } finally {
    conn.release();
  }
};

exports.getLiveBankBalances = async (req, res) => {
  try {
    const result = await bankModel.getBankCurrentBalances();
    res.json(result);
  } catch (err) {
    console.error("Balance calc error:", err);
    res.status(500).json({ error: err.message });
  }
};

exports.getLiveBanks = async (req, res) => {
  try {
    const result = await bankModel.getBanksWithLiveBalance();
    res.json(result);
  } catch (err) {
    console.error('Error fetching banks with live balances:', err);
    res.status(500).json({ error: err.message });
  }
};
