import type { APIRoute } from "astro";
import { prisma } from "../../lib/prisma";

export const prerender = false;

export const GET: APIRoute = async () => {
  try {
    const [paises, statuses, nacionalidades, form_versions] = await Promise.all([
      prisma.formulario.findMany({
        distinct: ["pais"],
        select: { pais: true },
        where: { pais: { not: null } },
      }),
      prisma.formulario.findMany({
        distinct: ["status"],
        select: { status: true },
      }),
      prisma.formulario.findMany({
        distinct: ["nacionalidad"],
        select: { nacionalidad: true },
        where: { nacionalidad: { not: null } },
      }),
      prisma.formulario.findMany({
        distinct: ["form_version"],
        select: { form_version: true },
        where: { form_version: { not: null } },
      }),
    ]);

    return Response.json({
      success: true,
      paises: paises
        .map((p) => p.pais)
        .filter((p): p is string => Boolean(p))
        .sort((a, b) => a.localeCompare(b, "es")),
      statuses: statuses
        .map((s) => s.status)
        .filter((s): s is string => Boolean(s))
        .sort(),
      nacionalidades: nacionalidades
        .map((n) => n.nacionalidad)
        .filter((n): n is string => Boolean(n))
        .sort((a, b) => a.localeCompare(b, "es")),
      form_versions: form_versions
        .map((f) => f.form_version)
        .filter((f): f is string => Boolean(f))
        .sort(),
    }, {
      headers: { "Cache-Control": "private, max-age=300, stale-while-revalidate=600" },
    });
  } catch (error) {
    console.error("Error en /api/admin/voluntarios/options:", error);
    return Response.json(
      { success: false, message: "Error al obtener opciones" },
      { status: 500 }
    );
  }
};
