/**
 * Cache management endpoints.
 *
 * GET    /cache/stats              → per-namespace stats
 * DELETE /cache                    → clear all
 * DELETE /cache/:namespace         → clear specific namespace
 * DELETE /cache?olderThan=<days>   → clear entries older than N days
 */
import type { FastifyInstance } from 'fastify';
import { FileCache } from '../proxymodel/file-cache.js';

export function registerCacheEndpoint(app: FastifyInstance): void {
  app.get('/cache/stats', async (_request, reply) => {
    const stats = FileCache.stats();
    reply.code(200).send(stats);
  });

  app.delete<{ Querystring: { olderThan?: string } }>('/cache', async (request, reply) => {
    const olderThanDays = request.query.olderThan ? Number(request.query.olderThan) : undefined;
    const opts: { olderThanMs?: number } = {};
    if (olderThanDays) opts.olderThanMs = olderThanDays * 24 * 60 * 60 * 1000;
    const result = FileCache.clear(opts);
    reply.code(200).send(result);
  });

  app.delete<{ Params: { namespace: string }; Querystring: { olderThan?: string } }>(
    '/cache/:namespace',
    async (request, reply) => {
      const olderThanDays = request.query.olderThan ? Number(request.query.olderThan) : undefined;
      const opts: { namespace: string; olderThanMs?: number } = { namespace: request.params.namespace };
      if (olderThanDays) opts.olderThanMs = olderThanDays * 24 * 60 * 60 * 1000;
      const result = FileCache.clear(opts);
      reply.code(200).send(result);
    },
  );
}
