import { Router } from 'express';
import { body, param, query } from 'express-validator';
import { list, create, update, remove } from '../controllers/expenseController.js';
import { protect } from '../middlewares/auth.js';
import { authorize } from '../middlewares/authorize.js';
import { ACTIONS } from '../utils/permissions.js';
import { handleValidation } from '../utils/handleValidation.js';

const router = Router();

const CATEGORIES = [
  'RENT', 'ELECTRICITY', 'SALARY', 'TRANSPORT', 'MAINTENANCE', 'MARKETING',
  'INTERNET', 'PACKAGING', 'BANK_CHARGES', 'MISCELLANEOUS', 'OTHER',
];
const PAYMENT_METHODS = ['CASH', 'UPI', 'CARD', 'BANK_TRANSFER', 'CHEQUE'];

const validateExpense = [
  body('expenseDate').isISO8601().withMessage('Valid expense date is required'),
  body('category').isIn(CATEGORIES).withMessage(`Category must be one of: ${CATEGORIES.join(', ')}`),
  body('amount').isFloat({ min: 0.01 }).withMessage('Amount must be greater than zero'),
  body('paymentMethod').optional().isIn(PAYMENT_METHODS).withMessage('Invalid payment method'),
  body('subcategory').optional({ nullable: true }).isString().trim().isLength({ max: 80 }),
  body('vendor').optional({ nullable: true }).isString().trim().isLength({ max: 120 }),
  body('referenceNumber').optional({ nullable: true }).isString().trim().isLength({ max: 60 }),
  body('description').optional({ nullable: true }).isString().trim().isLength({ max: 300 }),
  body('notes').optional({ nullable: true }).isString().trim().isLength({ max: 500 }),
];

router.use(protect, authorize(ACTIONS.EXPENSE_MANAGE));

router.get(
  '/',
  query('from').optional().isISO8601(),
  query('to').optional().isISO8601(),
  query('category').optional().isIn(CATEGORIES),
  query('page').optional().isInt({ min: 1 }),
  handleValidation,
  list
);
router.post('/', validateExpense, handleValidation, create);
router.put('/:id', param('id').isMongoId(), validateExpense, handleValidation, update);
router.delete('/:id', param('id').isMongoId(), handleValidation, remove);

export default router;
