import { Router, Request, Response, NextFunction } from 'express';
import { authenticate } from '../../middleware/auth.middleware';
import { requireRole } from '../../middleware/rbac.middleware';
import { env } from '../../config/env';
import { logger } from '../../utils/logger';
import { setServiceUp } from '../../utils/metrics';
import { isServiceOnline } from '../../utils/health-check';

const router = Router();
router.use(authenticate);
router.use(requireRole('SUPER_ADMIN'));

// Removed duplicated isServiceOnline - now using shared utility from utils/health-check.ts

// GET /api/services/status — check NocoDB, n8n, Gitea availability
router.get(
  '/status',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      const [nocodbOnline, n8nOnline, giteaOnline, mailhogOnline, miniqrOnline, excalidrawOnline, homepageOnline, vaultwardenOnline, rocketchatOnline, gancioOnline, jitsiOnline] = await Promise.all([
        isServiceOnline(env.NOCODB_URL),
        isServiceOnline(env.N8N_URL),
        isServiceOnline(env.GITEA_URL),
        isServiceOnline(env.MAILHOG_URL),
        isServiceOnline(env.MINI_QR_URL),
        isServiceOnline(env.EXCALIDRAW_URL),
        isServiceOnline(env.HOMEPAGE_URL),
        isServiceOnline(env.VAULTWARDEN_URL),
        isServiceOnline(`${env.ROCKETCHAT_URL}/api/info`),
        isServiceOnline(env.GANCIO_URL),
        isServiceOnline(env.JITSI_URL),
      ]);

      // Update Prometheus gauges
      setServiceUp('nocodb', nocodbOnline);
      setServiceUp('n8n', n8nOnline);
      setServiceUp('gitea', giteaOnline);
      setServiceUp('mailhog', mailhogOnline);
      setServiceUp('miniqr', miniqrOnline);
      setServiceUp('excalidraw', excalidrawOnline);
      setServiceUp('homepage', homepageOnline);
      setServiceUp('vaultwarden', vaultwardenOnline);
      setServiceUp('rocketchat', rocketchatOnline);
      setServiceUp('gancio', gancioOnline);
      setServiceUp('jitsi', jitsiOnline);

      res.json({
        nocodb: { online: nocodbOnline, url: env.NOCODB_URL },
        n8n: { online: n8nOnline, url: env.N8N_URL },
        gitea: { online: giteaOnline, url: env.GITEA_URL },
        mailhog: { online: mailhogOnline, url: env.MAILHOG_URL },
        miniqr: { online: miniqrOnline, url: env.MINI_QR_URL },
        excalidraw: { online: excalidrawOnline, url: env.EXCALIDRAW_URL },
        homepage: { online: homepageOnline, url: env.HOMEPAGE_URL },
        vaultwarden: { online: vaultwardenOnline, url: env.VAULTWARDEN_URL },
        rocketchat: { online: rocketchatOnline, url: env.ROCKETCHAT_URL },
        gancio: { online: gancioOnline, url: env.GANCIO_URL },
        jitsi: { online: jitsiOnline, url: env.JITSI_URL },
      });
    } catch (err) {
      logger.error('Failed to check services status', err);
      next(err);
    }
  },
);

// GET /api/services/config — return public-facing port numbers + subdomain info for iframe URLs
router.get(
  '/config',
  async (_req: Request, res: Response, _next: NextFunction) => {
    res.json({
      nocodbPort: env.NOCODB_EMBED_PORT,
      n8nPort: env.N8N_EMBED_PORT,
      giteaPort: env.GITEA_EMBED_PORT,
      mailhogPort: env.MAILHOG_EMBED_PORT,
      miniqrPort: env.MINI_QR_EMBED_PORT,
      excalidrawPort: env.EXCALIDRAW_EMBED_PORT,
      domain: env.DOMAIN,
      nocodbSubdomain: 'db',
      n8nSubdomain: 'n8n',
      giteaSubdomain: 'git',
      mailhogSubdomain: 'mail',
      miniqrSubdomain: 'qr',
      excalidrawSubdomain: 'draw',
      // Listmonk (newsletter platform)
      listmonkPort: env.LISTMONK_PROXY_PORT,
      listmonkSubdomain: 'listmonk',
      // Code Server (web IDE)
      codeServerPort: env.CODE_SERVER_PORT,
      codeServerSubdomain: 'code',
      // MkDocs (documentation)
      mkdocsPort: env.MKDOCS_PORT,
      mkdocsSubdomain: 'docs',
      // Grafana (metrics visualization)
      grafanaPort: env.GRAFANA_EMBED_PORT,
      grafanaSubdomain: 'grafana',
      // Alertmanager (alert routing)
      alertmanagerPort: env.ALERTMANAGER_EMBED_PORT,
      alertmanagerSubdomain: 'alertmanager',
      // Homepage (service dashboard)
      homepagePort: env.HOMEPAGE_EMBED_PORT,
      homepageSubdomain: 'home',
      // Vaultwarden (password manager)
      vaultwardenPort: env.VAULTWARDEN_EMBED_PORT,
      vaultwardenSubdomain: 'vault',
      // Rocket.Chat (team chat)
      rocketchatPort: env.ROCKETCHAT_EMBED_PORT,
      rocketchatSubdomain: 'chat',
      // Gancio (event management)
      gancioPort: env.GANCIO_EMBED_PORT,
      gancioSubdomain: 'events',
      // Jitsi Meet (video conferencing)
      jitsiPort: env.JITSI_EMBED_PORT,
      jitsiSubdomain: 'meet',
    });
  },
);

export const servicesRouter = router;
