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

const router = Router();

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

// ========== PAYMENTS (must be before /:id to avoid conflicts) ==========
// List payments
router.get('/payments', (req, res, next) => invoicesController.findAllPayments(req, res, next));

// Get payment by ID
router.get('/payments/:id', (req, res, next) => invoicesController.findPaymentById(req, res, next));

// Create payment
router.post('/payments', requireAccess({ roles: ['admin', 'manager', 'accountant'], permission: 'payments:create' }), (req, res, next) =>
  invoicesController.createPayment(req, res, next)
);

// Confirm payment
router.post('/payments/:id/confirm', requireAccess({ roles: ['admin', 'manager', 'accountant'], permission: 'payments:apply' }), (req, res, next) =>
  invoicesController.confirmPayment(req, res, next)
);

// Cancel payment
router.post('/payments/:id/cancel', requireAccess({ roles: ['admin', 'manager', 'accountant'], permission: 'payments:delete' }), (req, res, next) =>
  invoicesController.cancelPayment(req, res, next)
);

// ========== INVOICES ==========
// List invoices
router.get('/', (req, res, next) => invoicesController.findAll(req, res, next));

// Get invoice by ID
router.get('/:id', (req, res, next) => invoicesController.findById(req, res, next));

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

// Update invoice
router.patch('/:id', requireAccess({ roles: ['admin', 'manager', 'accountant'], permission: 'invoices:update' }), (req, res, next) =>
  invoicesController.update(req, res, next)
);

// Delete invoice
router.delete('/:id', requireAccess({ roles: ['admin'], permission: 'invoices:delete' }), (req, res, next) =>
  invoicesController.delete(req, res, next)
);

// Validate invoice (change status to validated)
router.post('/:id/validate', requireAccess({ roles: ['admin', 'manager', 'accountant'], permission: 'invoices:validate' }), (req, res, next) =>
  invoicesController.validate(req, res, next)
);

// Cancel invoice
router.post('/:id/cancel', requireAccess({ roles: ['admin', 'manager', 'accountant'], permission: 'invoices:cancel' }), (req, res, next) =>
  invoicesController.cancel(req, res, next)
);

export default router;
