const express = require('express');
const router = express.Router();
const {
  getAllTxnCategories,
  createTxnCategory,
  updateTxnCategory,
  deleteTxnCategory
} = require('../config/db');

// GET /api/txn-categories - Fetch all transaction categories
router.get('/', async (req, res) => {
  try {
    const categories = await getAllTxnCategories();
    res.json({ success: true, categories });
  } catch (error) {
    console.error('Error fetching transaction categories:', error);
    res.status(500).json({ success: false, message: 'Failed to fetch transaction categories' });
  }
});

// POST /api/txn-categories - Create new transaction category
router.post('/', async (req, res) => {
  try {
    const { name, type, status } = req.body;
    if (!name || !type) {
      return res.status(400).json({ success: false, message: 'Category Name and Type are required' });
    }

    const newCategory = await createTxnCategory({ name, type, status });
    res.status(201).json({ success: true, category: newCategory });
  } catch (error) {
    console.error('Error creating transaction category:', error);
    res.status(500).json({ success: false, message: 'Failed to create transaction category', error: error.message });
  }
});

// PUT /api/txn-categories/:id - Update existing transaction category
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { name, type, status } = req.body;
    if (!name || !type) {
      return res.status(400).json({ success: false, message: 'Category Name and Type are required' });
    }

    const updated = await updateTxnCategory(id, { name, type, status });
    res.json({ success: true, category: updated });
  } catch (error) {
    console.error('Error updating transaction category:', error);
    res.status(500).json({ success: false, message: 'Failed to update transaction category', error: error.message });
  }
});

// DELETE /api/txn-categories/:id - Delete transaction category
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    await deleteTxnCategory(id);
    res.json({ success: true, message: 'Category deleted successfully' });
  } catch (error) {
    console.error('Error deleting transaction category:', error);
    res.status(500).json({ success: false, message: 'Failed to delete transaction category' });
  }
});

module.exports = router;
