'use strict';

const PROTECTED_ROUTE_MODULES = Object.freeze([
  ['/api/dashboard', '../routes/dashboard'],
  ['/api/metas', '../routes/metas'],
  ['/api/reportes', '../routes/reportes'],
  ['/api/graficas', '../routes/graficas'],
  ['/api/ia', '../routes/ia'],
  ['/api/turnos', '../routes/turnos'],
  ['/api/mesas', '../routes/mesas'],
  ['/api/productos', '../routes/productos'],
  ['/api/meseros', '../routes/meseros'],
  ['/api/gastos', '../routes/gastos'],
  ['/api/retiros-caja', '../routes/retirosCaja'],
  ['/api/inventario', '../routes/inventario'],
  ['/api/insumos', '../routes/insumos'],
  ['/api/compras', '../routes/compras'],
  ['/api/productos-admin', '../routes/productosAdmin'],
  ['/api/mantenimiento', '../routes/mantenimiento'],
  ['/api/reporte-semanal', '../routes/reporteSemanal'],
  ['/api/actualizador', '../routes/actualizador'],
  ['/api/pagos', '../routes/pagos'],
  ['/api/v2/metricas', '../routes/v2/metricas'],
  ['/api/admin', '../routes/admin'],
  ['/api/notificaciones', '../routes/notificaciones'],
  ['/api/clientes', '../routes/clientes'],
]);

function registerPreAuthFeatureRoutes(app, { requireLicenseModule }) {
  app.use('/api/autofactura', requireLicenseModule('facturacion'), require('../modules/autofactura/autofactura.routes'));
}

function registerProtectedApiRoutes(app, dependencies) {
  const {
    authMiddleware,
    licenseGuard,
    requireLicenseModule,
    billingPrint,
    arkhonCard,
    offlineSync,
    limiterRefresh,
    limiterPDF,
    socketService,
    getPool,
  } = dependencies;

  app.use('/api', authMiddleware);
  app.use('/api/billing-print', require('../routes/billingPrint'));
  app.use('/api/license', require('../routes/license'));
  app.use('/api/security', require('../routes/security'));
  app.use('/api', licenseGuard);

  for (const [prefix, modulePath] of PROTECTED_ROUTE_MODULES) app.use(prefix, require(modulePath));

  app.use('/api/arkhon-card', requireLicenseModule('arkhon-card'), arkhonCard.routes);
  app.use('/api/admin/billing-print', requireLicenseModule('facturacion'), billingPrint.routes);
  app.use('/api/sync', offlineSync.routes);
  app.use('/api/sync-monitor', require('../modules/sync-monitor').routes);
  app.use('/api/whatsapp', requireLicenseModule('whatsapp'), require('../routes/whatsapp'));

  const billingController = require('../modules/billing/billing.controller');
  const { requireEngineeringAccess } = require('../modules/billing/billing.context');
  app.route('/api/billing/engineering-access')
    .get(requireEngineeringAccess({ allowLocalApi: false }), billingController.engineeringAccess)
    .post(requireEngineeringAccess({ allowLocalApi: false }), billingController.engineeringAccess);
  app.use('/api/billing', requireLicenseModule('facturacion'), require('../modules/billing/billing.routes'));

  app.post('/api/dashboard/refresh', limiterRefresh, async (req, res, next) => {
    try {
      const payload = await socketService.pollDB(true);
      res.json({ ok: true, mensaje: 'Dashboard actualizado', datos: payload });
    } catch (error) {
      next(error);
    }
  });

  app.get('/api/reporte-pdf', limiterPDF, require('../controllers/reportesController').getReportePDF);
  app.get('/api/fecha-hoy', async (_req, res, next) => {
    try {
      const pool = await getPool();
      const result = await pool.request().query('SELECT CAST(GETDATE() AS DATE) AS hoy');
      res.json({ ok: true, fecha: result.recordset[0].hoy.toISOString().split('T')[0] });
    } catch (error) {
      next(error);
    }
  });

  app.use('/api/api', (req, res) => res.redirect(307, `/api${req.url}`));
}

module.exports = { PROTECTED_ROUTE_MODULES, registerPreAuthFeatureRoutes, registerProtectedApiRoutes };
