import { NextResponse } from "next/server";

import { acessoDoPainel, pedidoDaPropriaTela, RECUSA_DE_ORIGEM, recusaDoPainel, revogarChave } from "@/lib/assistentes/painel";

export const runtime = "nodejs";

const SO_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

/**
 * Revoga uma chave. Ela para de valer no pedido seguinte do assistente e
 * continua na lista, como revogada, para o registro de atividade fazer sentido.
 */
export async function DELETE(request: Request, contexto: { params: Promise<{ id: string }> }) {
  if (!pedidoDaPropriaTela(request)) return RECUSA_DE_ORIGEM();
  const acesso = await acessoDoPainel();
  if (!acesso.ok) return recusaDoPainel(acesso.motivo);

  const { id } = await contexto.params;
  if (!SO_UUID.test(id)) return NextResponse.json({ error: "Chave inválida." }, { status: 400 });

  try {
    const revogada = await revogarChave(acesso, id);
    if (!revogada) return NextResponse.json({ error: "Chave não encontrada, ou já revogada." }, { status: 404 });
    return NextResponse.json({ ok: true }, { headers: { "Cache-Control": "no-store" } });
  } catch (erro) {
    console.error("[assistentes] não foi possível revogar a chave:", erro instanceof Error ? erro.message : erro);
    return NextResponse.json({ error: "Não foi possível revogar a chave." }, { status: 500 });
  }
}
