import { Router } from 'express';
import { body, param, query } from 'express-validator';
import { open, active, movement, movements, close, history, zReport } from '../controllers/shiftController.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 validateOpen = [
  body('register').isString().trim().isLength({ min: 1, max: 60 }).withMessage('Register/counter is required'),
  body('openingCash').isFloat({ min: 0 }).withMessage('Opening cash must be zero or more'),
  body('openingNote').optional({ nullable: true }).isString().trim().isLength({ max: 300 }),
];

const validateMovement = [
  param('id').isMongoId().withMessage('Invalid shift id'),
  body('type').isIn(['CASH_IN', 'CASH_OUT']).withMessage('Type must be CASH_IN or CASH_OUT'),
  body('amount').isFloat({ min: 0.01 }).withMessage('Amount must be greater than zero'),
  body('reason')
    .isIn(['PETTY_CASH', 'BANK_DEPOSIT', 'CHANGE_FUND', 'EXPENSE', 'OWNER_WITHDRAWAL', 'OTHER'])
    .withMessage('Invalid movement reason'),
  body('note').optional({ nullable: true }).isString().trim().isLength({ max: 300 }),
];

const validateClose = [
  param('id').isMongoId().withMessage('Invalid shift id'),
  body('actualCash').isFloat({ min: 0 }).withMessage('Actual counted cash is required'),
  body('closingNote').optional({ nullable: true }).isString().trim().isLength({ max: 500 }),
];

router.use(protect);

router.post('/', authorize(ACTIONS.SHIFT_OPEN), validateOpen, handleValidation, open);
router.get('/active', query('register').optional().isString().trim(), handleValidation, active);
router.post('/:id/movements', authorize(ACTIONS.POS_ACCESS), validateMovement, handleValidation, movement);
router.get('/:id/movements', param('id').isMongoId(), handleValidation, movements);
router.put(
  '/:id/close',
  authorize(ACTIONS.POS_ACCESS),
  validateClose,
  handleValidation,
  close
);
router.get('/', history);
router.get('/:id/z-report', param('id').isMongoId(), handleValidation, zReport);

export default router;
