import fp from 'fastify-plugin';
import type { FastifyPluginAsync } from 'fastify';
import { config } from '../config.js';

/**
 * Proxies all /dashboard/* requests to the dashboard-api service (port 4100).
 * The dashboard-api handles its own JWT auth, so these routes bypass control-api auth.
 */
const dashboardProxyPlugin: FastifyPluginAsync = async (fastify) => {
  fastify.all('/dashboard/*', { config: { public: true } }, async (request, reply) => {
    const target = `${config.dashboardApiUrl}${request.url}`;

    const headers: Record<string, string> = {
      'content-type': request.headers['content-type'] ?? 'application/json',
    };
    if (request.headers.authorization) {
      headers['authorization'] = request.headers.authorization;
    }

    const hasBody = request.method !== 'GET' && request.method !== 'HEAD';

    const upstream = await fetch(target, {
      method: request.method,
      headers,
      body: hasBody ? JSON.stringify(request.body) : undefined,
    });

    reply.status(upstream.status);

    const ct = upstream.headers.get('content-type');
    if (ct) reply.header('content-type', ct);

    return reply.send(await upstream.text());
  });
};

export default fp(dashboardProxyPlugin, { name: 'dashboard-proxy' });
