/**
 * AI Key Health Routes
 *
 * Super-admin endpoints to inspect and trigger the AI Key Health Check worker:
 *   GET  /api/ai-key-health/status  — worker status + last run summary
 *   POST /api/ai-key-health/run     — run a health-check pass immediately
 *
 * The worker itself runs automatically on an interval; these routes exist for
 * visibility and on-demand verification.
 */

import express, { Request, Response } from 'express';
import { authenticate, requireRole } from '../middleware/auth';
import { getModels } from '../models';
import { getAiKeyHealthWorker, runAiKeyHealthCheckOnce } from '../workers/aiKeyHealthWorker';

const router = express.Router();
router.use(authenticate);
router.use(requireRole('super-admin'));

router.get('/status', (_req: Request, res: Response) => {
  try {
    res.json(getAiKeyHealthWorker().getStatus());
  } catch (error: any) {
    res.status(500).json({ error: error?.message || 'Failed to read health status' });
  }
});

router.get('/logs', async (req: Request, res: Response) => {
  try {
    const { AiKeyHealthLog } = getModels();
    const limit = Math.min(parseInt(String(req.query.limit || '50'), 10) || 50, 200);
    const logs = AiKeyHealthLog
      ? await AiKeyHealthLog.find({}).sort({ createdAt: -1 }).limit(limit).lean()
      : [];
    res.json({ logs });
  } catch (error: any) {
    res.status(500).json({ error: error?.message || 'Failed to read health logs' });
  }
});

router.post('/run', async (_req: Request, res: Response) => {
  try {
    const summary = await runAiKeyHealthCheckOnce();
    res.json({ ok: true, summary });
  } catch (error: any) {
    res.status(500).json({ error: error?.message || 'Failed to run health check' });
  }
});

export default router;
