import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import type { Sql } from '../db.js';
import { fetchCapture, persistCapture } from '../services/capture-fetch.js';

/**
 * Register capture inspection routes.
 *
 * GET /api/capture/:providerId/:swapEntryId — fetch capture from host, persist trimmed copy
 */
export function registerCaptureRoutes(
  app: FastifyInstance,
  sql: Sql,
): void {
  app.get(
    '/api/capture/:providerId/:swapEntryId',
    async (req: FastifyRequest, reply: FastifyReply) => {
      const params = req.params as { providerId: string; swapEntryId: string };
      const swapEntryId = parseInt(params.swapEntryId, 10);

      if (isNaN(swapEntryId)) {
        return reply.status(400).send({ error: 'invalid swapEntryId' });
      }

      // Resolve host URL from control_hosts
      const hosts = await sql<{ ssh_host: string }[]>`
        SELECT ssh_host FROM control_hosts WHERE provider_id = ${params.providerId}
      `;

      if (hosts.length === 0 || !hosts[0]?.ssh_host) {
        return reply.status(404).send({ error: 'host not found or no SSH host configured' });
      }

      const baseUrl = `http://${hosts[0].ssh_host}:8401`;

      const result = await fetchCapture(baseUrl, params.providerId, swapEntryId);

      if (!result.ok) {
        return reply.status(404).send({ error: result.error });
      }

      // Persist trimmed copy
      try {
        await persistCapture(sql, result.capture!);
      } catch (err) {
        // Persistence failure is non-fatal — still return the capture
        app.log.warn({ err: (err as Error).message }, 'capture: persist failed');
      }

      return reply.send(result.capture);
    },
  );
}
