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

const router = Router();

const validateCreate = [
  body('name').isString().trim().isLength({ min: 2, max: 80 }).withMessage('Name must be 2-80 characters'),
  body('email').isEmail().withMessage('Valid email is required').normalizeEmail(),
  body('password').isString().isLength({ min: 6, max: 72 }).withMessage('Password must be at least 6 characters'),
  body('role')
    .isIn(['SUPER_ADMIN', 'ADMIN', 'MANAGER', 'CASHIER', 'INVENTORY_STAFF'])
    .withMessage('Invalid role'),
  body('phone').optional({ nullable: true }).isString().trim().isLength({ max: 20 }),
  body('employeeId').optional({ nullable: true }).isString().trim().isLength({ max: 40 }),
  body('status').optional().isIn(['ACTIVE', 'INACTIVE']).withMessage('Invalid status'),
  body('joiningDate').optional({ nullable: true }).isISO8601().withMessage('Invalid joining date'),
  body('notes').optional({ nullable: true }).isString().trim().isLength({ max: 500 }),
];

const validateUpdate = [
  param('id').isMongoId().withMessage('Invalid staff id'),
  body('name').optional().isString().trim().isLength({ min: 2, max: 80 }),
  body('email').optional().isEmail().normalizeEmail(),
  body('password').optional().isString().isLength({ min: 6, max: 72 }),
  body('role')
    .optional()
    .isIn(['SUPER_ADMIN', 'ADMIN', 'MANAGER', 'CASHIER', 'INVENTORY_STAFF'])
    .withMessage('Invalid role'),
  body('status').optional().isIn(['ACTIVE', 'INACTIVE']),
  body('phone').optional({ nullable: true }).isString().trim().isLength({ max: 20 }),
  body('employeeId').optional({ nullable: true }).isString().trim().isLength({ max: 40 }),
  body('notes').optional({ nullable: true }).isString().trim().isLength({ max: 500 }),
];

router.use(protect, authorize('staff.manage'));

router.get('/', query('search').optional().isString().trim(), handleValidation, list);
router.get('/permissions', permissions);
router.get('/:id', param('id').isMongoId(), handleValidation, getOne);
router.post('/', validateCreate, handleValidation, create);
router.put('/:id', validateUpdate, handleValidation, update);
router.patch('/:id/status', param('id').isMongoId(), body('status').isIn(['ACTIVE', 'INACTIVE']), handleValidation, setStatus);
router.delete('/:id', param('id').isMongoId(), handleValidation, remove);

export default router;
