/**
 * GET /api/v1/report/polygon-mapper
 * GET /api/v1/report/polygon-mapper/official-export
 */

import { Router, Request, Response } from 'express';
import { createRequire } from 'module';
import path from 'path';
import { cacheMiddleware } from '../middleware/cache';

const requireHere = createRequire(__filename);

type PolygonMapperLoader = {
  buildInternalPolygonMapperReport: () => Record<string, unknown>;
  buildOfficialPolygonTokenListEntries: () => unknown[];
  validatePolygonMapperConsistency: () => { ok: boolean; errors: string[]; warnings: string[] };
  resolvePolygonMeshAddress: (query: string) => Record<string, unknown> | null;
};

function loadPolygonMapperLoader(): PolygonMapperLoader | null {
  const candidates = [
    path.resolve(process.cwd(), 'config/polygon-official-mapper-loader.cjs'),
    path.resolve(process.cwd(), '..', 'config/polygon-official-mapper-loader.cjs'),
    path.resolve(process.cwd(), '..', '..', 'config/polygon-official-mapper-loader.cjs'),
    path.resolve(process.cwd(), '..', '..', '..', 'config/polygon-official-mapper-loader.cjs'),
    path.resolve(__dirname, '../../../../../config/polygon-official-mapper-loader.cjs'),
  ];

  for (const candidate of candidates) {
    try {
      return requireHere(candidate) as PolygonMapperLoader;
    } catch {
      // try next candidate
    }
  }
  return null;
}

const router: Router = Router();

router.get(
  '/polygon-mapper',
  cacheMiddleware(5 * 60 * 1000),
  (req: Request, res: Response) => {
    const loader = loadPolygonMapperLoader();
    if (!loader) {
      return res.status(503).json({
        error: 'Polygon official mapper config not available (run from monorepo with config/polygon-official-mapper.v1.json)',
      });
    }

    const report = loader.buildInternalPolygonMapperReport();
    const validation = loader.validatePolygonMapperConsistency();
    const query = typeof req.query.q === 'string' ? req.query.q.trim() : '';
    const match = query ? loader.resolvePolygonMeshAddress(query) : null;

    return res.json({
      ...report,
      validation,
      query: query || undefined,
      match: match || undefined,
      officialExportPath: '/api/v1/report/polygon-mapper/official-export',
    });
  },
);

router.get(
  '/polygon-mapper/official-export',
  cacheMiddleware(5 * 60 * 1000),
  (_req: Request, res: Response) => {
    const loader = loadPolygonMapperLoader();
    if (!loader) {
      return res.status(503).json({
        error: 'Polygon official mapper config not available (run from monorepo)',
      });
    }

    const report = loader.buildInternalPolygonMapperReport();
    return res.json({
      generatedAt: new Date().toISOString(),
      name: 'DBIS cW mesh (CCIP) → Polygon official mapped token list export',
      upstreamRepo: (report.officialPolygonTokenList as { upstreamRepo?: string } | undefined)?.upstreamRepo,
      upstreamMappedFile: (report.officialPolygonTokenList as { upstreamMappedFile?: string } | undefined)?.upstreamMappedFile,
      submissionDoc: (report.officialPolygonTokenList as { submissionDoc?: string } | undefined)?.submissionDoc,
      tokens: loader.buildOfficialPolygonTokenListEntries(),
    });
  },
);

export default router;
