import { Router } from "express";
import { getIndicators } from "../controllers/dashboardController";
import { verifyToken, authorizeModules } from "../middlewares/authJwt";
import {
  getStats,
  getAmountStats,
  getArrearsHistoryStats,
  getPaymentDelayHistoryStats,
  getPaymentsAndLiquidationsHistoryStats,
  getRecurringClientsIndicatorStats,
  getLiquidatedAmountsIndicatorStats,
} from "../controllers/customerHistoryController";

const dashboardRoutes = Router();

/**
 * @swagger
 * tags:
 *   name: Dashboard
 *   description: Indicadores y estadísticas del dashboard
 */

dashboardRoutes.use(verifyToken);
dashboardRoutes.use(authorizeModules("dashboard"));

/**
 * @swagger
 * /dashboard/indicators:
 *   get:
 *     operationId: getIndicators
 *     tags: [Dashboard]
 *     summary: Obtener indicadores
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: startDate
 *         schema:
 *           type: string
 *           format: date
 *         description: Fecha inicio (YYYY-MM-DD)
 *       - in: query
 *         name: endDate
 *         schema:
 *           type: string
 *           format: date
 *         description: Fecha fin (YYYY-MM-DD)
 *       - in: query
 *         name: currency
 *         schema:
 *           type: string
 *           enum: [VEF, USD]
 *           default: VEF
 *     responses:
 *       200:
 *         description: Indicadores obtenidos correctamente
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               required: [success, message, data]
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: true
 *                 message:
 *                   type: string
 *                   example: "Indicators retrieved successfully"
 *                 data:
 *                   type: object
 *                   properties:
 *                     operationCount:
 *                       type: number
 *                       description: Cantidad de operaciones en el período
 *                     operationAmount:
 *                       type: number
 *                       description: Monto total de operaciones
 *                     debtCount:
 *                       type: number
 *                       description: Cantidad de cuotas/pagos en el período
 *                     debtAmount:
 *                       type: number
 *                       description: Monto total de cuotas
 *             example:
 *               success: true
 *               message: "Indicators retrieved successfully"
 *               data:
 *                 operationCount: 45
 *                 operationAmount: 12500.50
 *                 debtCount: 120
 *                 debtAmount: 8900.25
 *       401:
 *         $ref: "#/components/responses/Unauthorized"
 *       403:
 *         $ref: "#/components/responses/Forbidden"
 */
dashboardRoutes.get("/indicators", getIndicators);

/**
 * @swagger
 * /dashboard/customer-history:
 *   get:
 *     operationId: getCustomerHistoryStats
 *     tags: [Dashboard]
 *     summary: Estadísticas de historial de clientes
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: take
 *         schema:
 *           type: integer
 *           default: 12
 *         description: Cantidad de meses a obtener
 *       - in: query
 *         name: year
 *         schema:
 *           type: integer
 *         description: Año específico (opcional)
 *     responses:
 *       200:
 *         description: Estadísticas obtenidas correctamente
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               required: [success, data]
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: true
 *                 data:
 *                   type: array
 *                   items:
 *                     type: object
 *                     properties:
 *                       _id:
 *                         type: object
 *                         properties:
 *                           year:
 *                             type: number
 *                           month:
 *                             type: number
 *                       statuses:
 *                         type: array
 *                         items:
 *                           type: object
 *                           properties:
 *                             status:
 *                               type: string
 *                             count:
 *                               type: number
 *                       total:
 *                         type: number
 *             example:
 *               success: true
 *               data:
 *                 - _id:
 *                     year: 2025
 *                     month: 3
 *                   statuses:
 *                     - status: "active"
 *                       count: 85
 *                     - status: "inactive"
 *                       count: 15
 *                   total: 100
 *       401:
 *         $ref: "#/components/responses/Unauthorized"
 *       403:
 *         $ref: "#/components/responses/Forbidden"
 */
dashboardRoutes.get("/customer-history", getStats);

/**
 * @swagger
 * /dashboard/amount-history:
 *   get:
 *     operationId: getAmountStats
 *     tags: [Dashboard]
 *     summary: Historial de montos (vigente, vencido, moroso) por mes
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: take
 *         schema:
 *           type: integer
 *           default: 12
 *       - in: query
 *         name: currency
 *         schema:
 *           type: string
 *           enum: [USD, VEF]
 *           default: USD
 *     responses:
 *       200:
 *         description: Historial obtenido correctamente
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               required: [success, data]
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: true
 *                 data:
 *                   type: array
 *                   items:
 *                     type: object
 *                     properties:
 *                       year:
 *                         type: number
 *                       month:
 *                         type: number
 *                       vigente:
 *                         type: number
 *                       vencido:
 *                         type: number
 *                       moroso:
 *                         type: number
 *             example:
 *               success: true
 *               data:
 *                 - year: 2025
 *                   month: 3
 *                   vigente: 15000.50
 *                   vencido: 2300.00
 *                   moroso: 1200.75
 *       400:
 *         description: Moneda inválida
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: false
 *                 message:
 *                   type: string
 *                   example: "Currency must be USD or VEF"
 *       401:
 *         $ref: "#/components/responses/Unauthorized"
 *       403:
 *         $ref: "#/components/responses/Forbidden"
 */
dashboardRoutes.get("/amount-history", getAmountStats);

/**
 * @swagger
 * /dashboard/arrears-history:
 *   get:
 *     operationId: getArrearsHistoryStats
 *     tags: [Dashboard]
 *     summary: Historial de mora por mes (clientes con 1, 2, 3, 4 o +4 cuotas morosas)
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: take
 *         schema:
 *           type: integer
 *           default: 12
 *     responses:
 *       200:
 *         description: Historial obtenido correctamente
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               required: [success, data]
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: true
 *                 data:
 *                   type: array
 *                   items:
 *                     type: object
 *                     properties:
 *                       year:
 *                         type: number
 *                       month:
 *                         type: number
 *                       one:
 *                         type: number
 *                         description: Clientes con 1 cuota morosa
 *                       two:
 *                         type: number
 *                         description: Clientes con 2 cuotas morosas
 *                       three:
 *                         type: number
 *                       four:
 *                         type: number
 *                       moreThan4:
 *                         type: number
 *                       totalClientsWithArrears:
 *                         type: number
 *             example:
 *               success: true
 *               data:
 *                 - year: 2025
 *                   month: 3
 *                   one: 5
 *                   two: 2
 *                   three: 1
 *                   four: 0
 *                   moreThan4: 1
 *                   totalClientsWithArrears: 9
 *       401:
 *         $ref: "#/components/responses/Unauthorized"
 *       403:
 *         $ref: "#/components/responses/Forbidden"
 */
dashboardRoutes.get("/arrears-history", getArrearsHistoryStats);

/**
 * @swagger
 * /dashboard/payment-delay-history:
 *   get:
 *     operationId: getPaymentDelayHistoryStats
 *     tags: [Dashboard]
 *     summary: Historial de retraso de pagos (días desde creación hasta pago)
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: take
 *         schema:
 *           type: integer
 *           default: 12
 *     responses:
 *       200:
 *         description: Historial obtenido correctamente
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               required: [success, data]
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: true
 *                 data:
 *                   type: array
 *                   items:
 *                     type: object
 *                     properties:
 *                       year:
 *                         type: number
 *                       month:
 *                         type: number
 *                       totalPaidInstallments:
 *                         type: number
 *                       averageDays:
 *                         type: number
 *                         description: Días promedio desde creación hasta pago
 *                       lt14:
 *                         type: number
 *                         description: Cuotas pagadas en menos de 14 días
 *                       d14to15:
 *                         type: number
 *                       d15to20:
 *                         type: number
 *                       d21to30:
 *                         type: number
 *                       d31to60:
 *                         type: number
 *                       d61to90:
 *                         type: number
 *                       d91plus:
 *                         type: number
 *             example:
 *               success: true
 *               data:
 *                 - year: 2025
 *                   month: 3
 *                   totalPaidInstallments: 85
 *                   averageDays: 12.5
 *                   lt14: 60
 *                   d14to15: 15
 *                   d15to20: 8
 *                   d21to30: 2
 *                   d31to60: 0
 *                   d61to90: 0
 *                   d91plus: 0
 *       401:
 *         $ref: "#/components/responses/Unauthorized"
 *       403:
 *         $ref: "#/components/responses/Forbidden"
 */
dashboardRoutes.get("/payment-delay-history", getPaymentDelayHistoryStats);

/**
 * @swagger
 * /dashboard/payments-liquidations-history:
 *   get:
 *     operationId: getPaymentsAndLiquidationsHistoryStats
 *     tags: [Dashboard]
 *     summary: Historial de pagos y liquidaciones por mes
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: take
 *         schema:
 *           type: integer
 *           default: 12
 *       - in: query
 *         name: currency
 *         schema:
 *           type: string
 *           enum: [USD, VEF]
 *           default: VEF
 *     responses:
 *       200:
 *         description: Historial obtenido correctamente
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               required: [success, data]
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: true
 *                 data:
 *                   type: array
 *                   items:
 *                     type: object
 *                     properties:
 *                       year:
 *                         type: number
 *                       month:
 *                         type: number
 *                       paymentsAmount:
 *                         type: number
 *                       paymentsCount:
 *                         type: number
 *                       liquidationsAmount:
 *                         type: number
 *                       liquidationsCount:
 *                         type: number
 *             example:
 *               success: true
 *               data:
 *                 - year: 2025
 *                   month: 3
 *                   paymentsAmount: 45000.00
 *                   paymentsCount: 120
 *                   liquidationsAmount: 38000.50
 *                   liquidationsCount: 45
 *       400:
 *         description: Moneda inválida
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: false
 *                 message:
 *                   type: string
 *                   example: "Currency must be USD or VEF"
 *       401:
 *         $ref: "#/components/responses/Unauthorized"
 *       403:
 *         $ref: "#/components/responses/Forbidden"
 */
dashboardRoutes.get(
  "/payments-liquidations-history",
  getPaymentsAndLiquidationsHistoryStats,
);

/**
 * @swagger
 * /dashboard/recurring-clients-indicator:
 *   get:
 *     operationId: getRecurringClientsIndicatorStats
 *     tags: [Dashboard]
 *     summary: Indicador de clientes recurrentes (más de 1 crédito en el rango)
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: startDate
 *         schema:
 *           type: string
 *           format: date
 *         description: Fecha inicio (YYYY-MM-DD)
 *       - in: query
 *         name: endDate
 *         schema:
 *           type: string
 *           format: date
 *         description: Fecha fin (YYYY-MM-DD)
 *       - in: query
 *         name: currency
 *         schema:
 *           type: string
 *           enum: [USD, VEF]
 *           default: VEF
 *     responses:
 *       200:
 *         description: Indicador obtenido correctamente
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               required: [success, data]
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: true
 *                 data:
 *                   type: array
 *                   items:
 *                     type: object
 *                     properties:
 *                       clientId:
 *                         type: string
 *                       clientName:
 *                         type: string
 *                       creditsCount:
 *                         type: number
 *                       approvedAmount:
 *                         type: number
 *             example:
 *               success: true
 *               data:
 *                 - clientId: "507f1f77bcf86cd799439011"
 *                   clientName: "Juan Pérez"
 *                   creditsCount: 5
 *                   approvedAmount: 2500.00
 *                 - clientId: "507f1f77bcf86cd799439012"
 *                   clientName: "María García"
 *                   creditsCount: 3
 *                   approvedAmount: 1800.50
 *       400:
 *         description: Moneda inválida
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: false
 *                 message:
 *                   type: string
 *                   example: "Currency must be USD or VEF"
 *       401:
 *         $ref: "#/components/responses/Unauthorized"
 *       403:
 *         $ref: "#/components/responses/Forbidden"
 */
dashboardRoutes.get(
  "/recurring-clients-indicator",
  getRecurringClientsIndicatorStats,
);

/**
 * @swagger
 * /dashboard/liquidated-amounts-indicator:
 *   get:
 *     operationId: getLiquidatedAmountsIndicatorStats
 *     tags: [Dashboard]
 *     summary: Indicador de montos liquidados (vigentes, vencidos, morosos)
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: currency
 *         schema:
 *           type: string
 *           enum: [USD, VEF]
 *         description: Moneda de los montos
 *     responses:
 *       200:
 *         description: Indicador obtenido correctamente
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               required: [success, data]
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: true
 *                 data:
 *                   type: object
 *                   properties:
 *                     liquidadosVigentes:
 *                       type: number
 *                       description: Monto vigente (fecha >= hoy)
 *                     liquidadosVencidos:
 *                       type: number
 *                       description: Monto vencido (1-2 días)
 *                     liquidadosMorosos:
 *                       type: number
 *                       description: Monto moroso (+2 días)
 *                     total:
 *                       type: number
 *                     currency:
 *                       type: string
 *                       enum: [USD, VEF]
 *             example:
 *               success: true
 *               data:
 *                 liquidadosVigentes: 25000.00
 *                 liquidadosVencidos: 3500.50
 *                 liquidadosMorosos: 1200.75
 *                 total: 29701.25
 *                 currency: "VEF"
 *       400:
 *         description: Moneda inválida
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: false
 *                 message:
 *                   type: string
 *                   example: "Currency must be USD or VEF"
 *       401:
 *         $ref: "#/components/responses/Unauthorized"
 *       403:
 *         $ref: "#/components/responses/Forbidden"
 */
dashboardRoutes.get(
  "/liquidated-amounts-indicator",
  getLiquidatedAmountsIndicatorStats,
);

export default dashboardRoutes;
