import { Router } from 'express';
import { query } from 'express-validator';
import profitReportService from '../services/profitReportService.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 PRESETS = ['TODAY', 'YESTERDAY', 'THIS_WEEK', 'THIS_MONTH', 'LAST_MONTH', 'THIS_YEAR', 'CUSTOM'];

const validateRange = [
  query('preset').optional().isIn(PRESETS).withMessage(`Preset must be one of: ${PRESETS.join(', ')}`),
  query('from').optional().isISO8601().withMessage('Invalid from date'),
  query('to').optional().isISO8601().withMessage('Invalid to date'),
  query('paymentMethod').optional().isIn(['CASH', 'UPI', 'CARD']),
  query('cashierId').optional({ checkFalsy: true }).isMongoId().withMessage('Invalid cashier id'),
  handleValidation,
];

router.use(protect, authorize(ACTIONS.REPORTS_VIEW_FINANCIAL), validateRange);

const send = (res, data) => res.json({ success: true, data });

router.get('/summary', async (req, res, next) => {
  try {
    send(res, await profitReportService.getProfitSummary(req.query));
  } catch (e) {
    next(e);
  }
});

router.get('/products', async (req, res, next) => {
  try {
    const rows = await profitReportService.getProductProfit(req.query);
    send(res, { rows });
  } catch (e) {
    next(e);
  }
});

router.get('/categories', async (req, res, next) => {
  try {
    const rows = await profitReportService.getCategoryProfit(req.query);
    send(res, { rows });
  } catch (e) {
    next(e);
  }
});

router.get('/expenses-breakdown', async (req, res, next) => {
  try {
    send(res, await profitReportService.getExpenseBreakdown(req.query));
  } catch (e) {
    next(e);
  }
});

router.get('/net-profit', async (req, res, next) => {
  try {
    send(res, await profitReportService.getNetProfitReport(req.query));
  } catch (e) {
    next(e);
  }
});

export default router;
