import { NextResponse } from "next/server";

import { avisoDaSpedyAutentico, processarAvisoDaSpedy } from "@/lib/fiscal/servidor/avisos-spedy";
import { acordarFila } from "@/lib/fiscal/servidor/fila";
import { createAdminClient } from "@/lib/supabase-server";

export const runtime = "nodejs";

/**
 * Avisos da Spedy (`invoice.status_changed`), assinados no padrão Standard
 * Webhooks. O corpo é lido CRU antes de qualquer parse: é sobre ele que a
 * assinatura é feita.
 *
 * Responde 200 depressa sempre que o aviso é autêntico, mesmo que a nota não
 * seja deste servidor: cinco falhas seguidas desligam o aviso da conta inteira.
 */
export async function POST(req: Request) {
  const corpoCru = await req.text();
  const cabecalhos = {
    id: req.headers.get("webhook-id"),
    timestamp: req.headers.get("webhook-timestamp"),
    assinatura: req.headers.get("webhook-signature"),
  };

  if (!(await avisoDaSpedyAutentico(cabecalhos, corpoCru))) {
    return NextResponse.json({ error: "Assinatura inválida." }, { status: 401 });
  }

  let aviso: { id?: unknown; event?: unknown; data?: unknown };
  try {
    aviso = JSON.parse(corpoCru);
  } catch {
    return NextResponse.json({ error: "Corpo inválido." }, { status: 400 });
  }

  const id = String(aviso.id || cabecalhos.id || "");
  const evento = String(aviso.event || "");
  if (!id || !evento) return NextResponse.json({ ok: true });

  try {
    const resultado = await processarAvisoDaSpedy(createAdminClient(), { id, event: evento, data: aviso.data });
    acordarFila();
    return NextResponse.json({ ok: true, resultado: resultado.resultado });
  } catch (erro) {
    console.error("[fiscal] aviso da Spedy não processado", id, erro instanceof Error ? erro.message : erro);
    /* 500 faz a Spedy tentar de novo mais tarde; a fila também consulta sozinha. */
    return NextResponse.json({ error: "Falha ao processar." }, { status: 500 });
  }
}
