const express = require('express');
const router = express.Router();
const {
  getAllTransactions,
  getTransactionById,
  createManualTransaction,
  updateTransaction,
  deleteTransaction
} = require('../config/db');

// GET /api/transactions - Single Ledger (Invoice Payments + Manual Income & Expense)
router.get('/', async (req, res) => {
  try {
    const transactions = await getAllTransactions();
    res.json({ success: true, transactions });
  } catch (error) {
    console.error('Error fetching ledger transactions:', error);
    res.status(500).json({ success: false, message: 'Failed to fetch ledger transactions' });
  }
});

// POST /api/transactions - Create standalone Manual Transaction (Income or Expense)
router.post('/', async (req, res) => {
  try {
    const { type, amount, category_id, customer_id, payment_method, reference, note, attachment, txn_date } = req.body;
    if (!type || !amount || Number(amount) <= 0) {
      return res.status(400).json({ success: false, message: 'Transaction Type and positive Amount are required' });
    }

    const transaction = await createManualTransaction({
      type,
      amount,
      category_id,
      customer_id,
      payment_method,
      reference,
      note,
      attachment,
      txn_date
    });

    res.status(201).json({ success: true, transaction, message: 'Manual transaction recorded in ledger' });
  } catch (error) {
    console.error('Error recording manual transaction:', error);
    res.status(500).json({ success: false, message: 'Failed to record manual transaction' });
  }
});

// GET /api/transactions/:id - Fetch single transaction
router.get('/:id', async (req, res) => {
  try {
    const transaction = await getTransactionById(req.params.id);
    if (!transaction) {
      return res.status(404).json({ success: false, message: 'Transaction not found' });
    }
    res.json({ success: true, transaction });
  } catch (error) {
    console.error('Error fetching transaction:', error);
    res.status(500).json({ success: false, message: 'Failed to fetch transaction' });
  }
});

// PUT /api/transactions/:id - Update transaction
router.put('/:id', async (req, res) => {
  try {
    const transaction = await updateTransaction(req.params.id, req.body);
    if (!transaction) {
      return res.status(404).json({ success: false, message: 'Transaction not found' });
    }
    res.json({ success: true, transaction, message: 'Transaction updated successfully' });
  } catch (error) {
    console.error('Error updating transaction:', error);
    res.status(500).json({ success: false, message: 'Failed to update transaction' });
  }
});

// DELETE /api/transactions/:id - Delete transaction
router.delete('/:id', async (req, res) => {
  try {
    const success = await deleteTransaction(req.params.id);
    if (!success) {
      return res.status(404).json({ success: false, message: 'Transaction not found or could not be deleted' });
    }
    res.json({ success: true, message: 'Transaction deleted successfully' });
  } catch (error) {
    console.error('Error deleting transaction:', error);
    res.status(500).json({ success: false, message: 'Failed to delete transaction' });
  }
});

module.exports = router;
