import { Router } from 'express';
import { body, param } from 'express-validator';
import { authenticate, authorize } from '../../shared/middleware/auth';
import { validate } from '../../shared/middleware/validation';
import { suppliersController } from './suppliers.controller';

const router = Router();

router.use(authenticate);

router.get('/', authorize('suppliers', 'suppliers', 'read'), suppliersController.findAll);
router.get('/stats', authorize('suppliers', 'suppliers', 'read'), suppliersController.getStats);
router.get('/export', authorize('suppliers', 'suppliers', 'read'), suppliersController.export);

router.get(
  '/:id',
  authorize('suppliers', 'suppliers', 'read'),
  param('id').isUUID(),
  validate,
  suppliersController.findById
);

router.post(
  '/',
  authorize('suppliers', 'suppliers', 'create'),
  [
    body('name').optional({ values: 'falsy' }).trim(),
    body('companyName').optional({ values: 'falsy' }).trim(),
    body('email')
      .optional({ values: 'falsy' })
      .custom((value) => {
        if (value === null || value === undefined || value === '') return true;
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
      })
      .withMessage('Invalid email format'),
    validate,
  ],
  suppliersController.create
);

router.put(
  '/:id',
  authorize('suppliers', 'suppliers', 'update'),
  [
    param('id').isUUID(),
    body('email')
      .optional({ values: 'falsy' })
      .custom((value) => {
        if (value === null || value === undefined || value === '') return true;
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
      })
      .withMessage('Invalid email format'),
    validate,
  ],
  suppliersController.update
);

router.post(
  '/:id/archive',
  authorize('suppliers', 'suppliers', 'archive'),
  param('id').isUUID(),
  validate,
  suppliersController.archive
);

export default router;
