import type { APIRoute } from 'astro';

const DIRECTUS_URL =
  import.meta.env.DIRECTUS_URL ||
  process.env.DIRECTUS_URL ||
  'http://localhost:8055';

const DIRECTUS_TOKEN =
  import.meta.env.DIRECTUS_TOKEN ||
  process.env.DIRECTUS_TOKEN ||
  '';

// Proxy auth des fichiers Directus -> permet au browser de les charger
// sans necessiter de permission publique sur directus_files.
//
// Usage frontend : /api/files/<uuid>?width=1200&quality=80&fit=cover
export const GET: APIRoute = async ({ params, url }) => {
  const id = params.id;
  if (!id) return new Response('Missing id', { status: 400 });

  // Forward les query params de transform (width, height, quality, fit, format)
  const search = url.searchParams.toString();
  const target = `${DIRECTUS_URL}/assets/${id}${search ? `?${search}` : ''}`;

  const headers: Record<string, string> = {};
  if (DIRECTUS_TOKEN) headers.Authorization = `Bearer ${DIRECTUS_TOKEN}`;

  const res = await fetch(target, { headers });
  if (!res.ok) {
    return new Response(`Upstream ${res.status}`, { status: res.status });
  }

  // Stream la reponse directement au browser avec les headers content-*
  const upstream = new Headers(res.headers);
  // Cache 1 jour cote browser (les UUID sont immuables)
  upstream.set('Cache-Control', 'public, max-age=86400, immutable');

  return new Response(res.body, { status: 200, headers: upstream });
};
