/**
 * GET /api/v1/report/official-protocols
 * GET /api/v1/report/official-protocols/:protocolId
 */

import { Router, Request, Response } from 'express';
import { cacheMiddleware } from '../middleware/cache';
import { buildOfficialProtocolsReport } from '../../services/official-protocols-report';
import { verifyProtocolContracts } from '../../services/official-protocols-verification';

const router: Router = Router();

router.get(
  '/official-protocols',
  cacheMiddleware(5 * 60 * 1000),
  (req: Request, res: Response) => {
    const protocolId = typeof req.query.id === 'string' ? req.query.id.trim() : null;
    const report = buildOfficialProtocolsReport(protocolId);
    if (!report) {
      return res.status(503).json({
        error: 'Official protocol registry not available (run from monorepo with config/chain138-official-protocol-contracts.json)',
      });
    }
    return res.json(report);
  },
);

router.get(
  '/official-protocols/:protocolId',
  cacheMiddleware(5 * 60 * 1000),
  async (req: Request, res: Response) => {
    const protocolId = String(req.params.protocolId ?? '').trim();
    const report = buildOfficialProtocolsReport(protocolId);
    if (!report) {
      return res.status(503).json({
        error: 'Official protocol registry not available (run from monorepo)',
      });
    }
    if (report.protocols.length === 0) {
      return res.status(404).json({ error: 'Protocol not found', protocolId });
    }
    const protocol = report.protocols[0];
    const verification = await verifyProtocolContracts(report.chainId, protocol.contracts);
    return res.json({
      ...report,
      protocol,
      verification,
    });
  },
);

export default router;
