const express = require('express');
const router = express.Router();
const {
  getAllPaymentAccounts,
  createPaymentAccount,
  deletePaymentAccount
} = require('../config/db');

// GET /api/payment-accounts - Get all bank and MFS accounts
router.get('/', async (req, res) => {
  try {
    const accounts = await getAllPaymentAccounts();
    res.json({ success: true, accounts });
  } catch (error) {
    console.error('Error fetching payment accounts:', error);
    res.status(500).json({ success: false, message: 'Failed to fetch payment accounts' });
  }
});

// POST /api/payment-accounts - Add new bank or MFS account
router.post('/', async (req, res) => {
  try {
    const { type, bank_name, branch_name, holder_name, account_number, routing_number } = req.body;
    if (!bank_name || !account_number) {
      return res.status(400).json({ success: false, message: 'Bank/Account Name and Account Number are required' });
    }

    const newAccount = await createPaymentAccount({ type, bank_name, branch_name, holder_name, account_number, routing_number });
    res.status(201).json({ success: true, account: newAccount });
  } catch (error) {
    console.error('Error creating payment account:', error);
    res.status(500).json({ success: false, message: 'Failed to create payment account' });
  }
});

// DELETE /api/payment-accounts/:id - Delete account
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    await deletePaymentAccount(id);
    res.json({ success: true, message: 'Payment account deleted successfully' });
  } catch (error) {
    console.error('Error deleting payment account:', error);
    res.status(500).json({ success: false, message: 'Failed to delete payment account' });
  }
});

module.exports = router;
