import { Router, type IRouter } from 'express';
import { authenticate, authorize } from '../middlewares/auth.middleware.js';
import { strictLimit } from '../middlewares/rate-limit.middleware.js';
import * as subscriptionController from '../controllers/subscription.controller.js';

const router: IRouter = Router();

// All endpoints require authentication + admin role
router.use(authenticate);
router.use(authorize('owner', 'cfo'));

// (Endpoints /plans y /plans/:id eliminados con el modelo PlanPrice legacy.
// Para precios despacho usa /api/planes/despacho.)

// Self-serve: el usuario actúa sobre el tenant de su JWT
router.post('/me/trial', subscriptionController.startMyTrial);
// 10/hora — crea preapprovals/preferences en MercadoPago (side-effect en tercero)
router.post('/me/subscribe', strictLimit, subscriptionController.subscribeMe);
router.post('/me/change', strictLimit, subscriptionController.changeMyPlan);
router.post('/me/upgrade', strictLimit, subscriptionController.upgradeMe);
router.post('/me/upgrade/cancel', subscriptionController.cancelMyPendingUpgrade);
router.post('/me/cancel', subscriptionController.cancelMySubscription);
router.post('/me/reactivate', subscriptionController.reactivateMe);
router.get('/me/addons', subscriptionController.getMyAddons);
router.post('/me/addons', strictLimit, subscriptionController.addMyAddon);
router.delete('/me/addons/:addonId', subscriptionController.cancelMyAddon);

// Listar todas las suscripciones (global admin)
router.get('/', subscriptionController.getAllSubscriptions);

// Admin subscription management (global admin verified in controller)
router.get('/:tenantId', subscriptionController.getSubscription);
router.post('/:tenantId/generate-link', subscriptionController.generatePaymentLink);
router.post('/:tenantId/mark-paid', subscriptionController.markAsPaid);
router.get('/:tenantId/payments', subscriptionController.getPayments);

export { router as subscriptionRoutes };
