import { getAdmin } from "../../../../../lib/admin-auth";
import { audit } from "../../../../../lib/admin-operations";
import { DB } from "../../../../../server/database.ts";
import { csvCell } from "../../../../../server/csv.ts";
export async function GET() {
  const admin = await getAdmin();
  if (!admin) return Response.json({ error: "unauthorized" }, { status: 401 });
  await audit(admin.userId, "APPLICATIONS_EXPORTED", "APPLICATION", "ALL");
  const headers = [
      "referencia",
      "estado",
      "submetida_em",
      "resposta",
      "crianca",
      "nascimento",
      "nif",
      "niss",
      "encarregado",
      "email",
      "telefone",
      "documentos",
    ],
    encoder = new TextEncoder();
  let cursor = "",
    first = true;
  const stream = new ReadableStream<Uint8Array>({
    async pull(controller) {
      if (first) {
        controller.enqueue(
          encoder.encode("\uFEFF" + headers.map(csvCell).join(";") + "\r\n"),
        );
        first = false;
      }
      const rows = await DB.prepare(
        "SELECT a.id,a.public_number referencia,a.status estado,a.submitted_at submetida_em,s.name resposta,c.full_name crianca,c.birth_date nascimento,c.tax_number nif,c.social_security_number niss,g.full_name encarregado,g.email,g.phone telefone,(SELECT count(*) FROM documents d WHERE d.application_id=a.id) documentos FROM applications a JOIN children c ON c.application_id=a.id JOIN social_responses s ON s.id=a.social_response_id LEFT JOIN guardians g ON g.application_id=a.id AND g.is_education_guardian=1 WHERE a.deleted_at IS NULL AND a.id>? ORDER BY a.id LIMIT 200",
      )
        .bind(cursor)
        .all<Record<string, string | number | null>>();
      if (!rows.results.length) {
        controller.close();
        return;
      }
      cursor = String(rows.results.at(-1)!.id);
      controller.enqueue(
        encoder.encode(
          rows.results
            .map((row) => headers.map((h) => csvCell(row[h])).join(";"))
            .join("\r\n") + "\r\n",
        ),
      );
    },
  });
  return new Response(stream, {
    headers: {
      "content-type": "text/csv; charset=utf-8",
      "content-disposition": `attachment; filename="inscricoes-${new Date().toISOString().slice(0, 10)}.csv"`,
      "cache-control": "private, no-store",
    },
  });
}
