import { Router } from 'express';
import { cfdiController } from './cfdi.controller.js';
import { authenticate } from '../../shared/middleware/auth.middleware.js';
import { requireAccess } from '../../shared/middleware/rbac.middleware.js';

const router = Router();

// All CFDI routes require authentication
router.use(authenticate);

// ============================================================================
// CERTIFICATE ROUTES (must be before /:id routes to avoid conflicts)
// ============================================================================

// List certificates (admin, manager, accountant)
router.get(
  '/certificates',
  requireAccess({ roles: ['admin', 'manager', 'accountant'], permission: 'cfdi:read' }),
  (req, res, next) => cfdiController.listCertificates(req, res, next)
);

// Upload certificate (admin only)
router.post(
  '/certificates',
  requireAccess({ roles: ['admin'], permission: 'cfdi:manage_certificates' }),
  (req, res, next) => cfdiController.uploadCertificate(req, res, next)
);

// ============================================================================
// CFDI INVOICE ROUTES
// ============================================================================

// List CFDIs (admin, manager, accountant)
router.get(
  '/',
  requireAccess({ roles: ['admin', 'manager', 'accountant'], permission: 'cfdi:read' }),
  (req, res, next) => cfdiController.findAll(req, res, next)
);

// Get CFDI by ID (admin, manager, accountant)
router.get(
  '/:id',
  requireAccess({ roles: ['admin', 'manager', 'accountant'], permission: 'cfdi:read' }),
  (req, res, next) => cfdiController.findById(req, res, next)
);

// Get CFDI status (admin, manager, accountant)
router.get(
  '/:id/status',
  requireAccess({ roles: ['admin', 'manager', 'accountant'], permission: 'cfdi:read' }),
  (req, res, next) => cfdiController.getStatus(req, res, next)
);

// Create CFDI (admin, manager, accountant)
router.post(
  '/',
  requireAccess({ roles: ['admin', 'manager', 'accountant'], permission: 'cfdi:create' }),
  (req, res, next) => cfdiController.create(req, res, next)
);

// Update draft CFDI (admin, manager, accountant)
router.put(
  '/:id',
  requireAccess({ roles: ['admin', 'manager', 'accountant'], permission: 'cfdi:update' }),
  (req, res, next) => cfdiController.update(req, res, next)
);

// Request stamping (admin, manager, accountant)
router.post(
  '/:id/stamp',
  requireAccess({ roles: ['admin', 'manager', 'accountant'], permission: 'cfdi:stamp' }),
  (req, res, next) => cfdiController.requestStamp(req, res, next)
);

// Request cancellation (admin, manager)
router.post(
  '/:id/cancel',
  requireAccess({ roles: ['admin', 'manager'], permission: 'cfdi:cancel' }),
  (req, res, next) => cfdiController.requestCancellation(req, res, next)
);

export default router;
