import type { FastifyInstance } from 'fastify';
import type { FastifySchema } from 'fastify';
import type { Authenticate } from '../../../shared/auth.js';
import { requireRole } from '../../../shared/auth.js';
import { errorSchema } from '../../../shared/swagger.js';
import { CacheService } from '../application/cache-service.js';

export interface CacheRoutesDeps {
  cache: CacheService;
  authenticate: Authenticate;
}

export async function registerCacheRoutes(
  app: FastifyInstance,
  deps: CacheRoutesDeps,
): Promise<void> {
  const contractsSchema: FastifySchema = {
    tags: ['Admin'],
    summary: 'List cache contracts (admin)',
    response: { 401: errorSchema, 403: errorSchema },
  };
  app.get('/cache/contracts', { schema: contractsSchema }, async (request, reply) => {
    const user = await deps.authenticate(request);
    requireRole(user, 'admin');
    return reply.send({ items: deps.cache.listContracts() });
  });

  const cacheMetricsSchema: FastifySchema = {
    tags: ['Admin'],
    summary: 'Cache metrics',
    response: { 401: errorSchema },
  };
  app.get('/cache/metrics', { schema: cacheMetricsSchema }, async (request, reply) => {
    await deps.authenticate(request);
    return reply.send(deps.cache.metrics());
  });
}
