import { notaParaTela } from "@/lib/fiscal/servidor/apresentacao";
import { descartarPrevia, notaDaEmpresa } from "@/lib/fiscal/servidor/notas";
import { exigirUuid, rotaFiscal } from "@/lib/fiscal/servidor/rota";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

type Contexto = { params: Promise<{ id: string }> };

export async function GET(_req: Request, { params }: Contexto) {
  const { id } = await params;
  return rotaFiscal("fiscal.ver", async ({ admin, empresaId }) => {
    const nota = await notaDaEmpresa(admin, empresaId, exigirUuid(id, "Nota"));
    const [eventosR, pedidoR] = await Promise.all([
      admin.from("fiscal_eventos").select("id,tipo,titulo,detalhe,ator,created_at").eq("nota_id", nota.id).order("created_at", { ascending: false }).limit(100),
      nota.pedido_id
        ? admin.from("orders").select("id,number").eq("id", nota.pedido_id).eq("user_id", empresaId).maybeSingle()
        : Promise.resolve({ data: null }),
    ]);
    const eventos = (eventosR.data ?? []) as Array<{ ator: string | null }>;
    const atores = [...new Set(eventos.map((e) => e.ator).filter((a): a is string => Boolean(a)))];
    const nomes = new Map<string, string>();
    if (atores.length) {
      const [{ data: perfis }, { data: equipe }, { data: contas }] = await Promise.all([
        admin.from("profiles").select("id,store_name").in("id", atores),
        admin.from("employee_profiles").select("user_id,full_name").in("user_id", atores),
        admin.from("company_users").select("user_id,email").in("user_id", atores),
      ]);
      for (const c of (contas ?? []) as Array<{ user_id: string; email: string | null }>) if (c.email) nomes.set(c.user_id, c.email);
      for (const p of (perfis ?? []) as Array<{ id: string; store_name: string | null }>) if (p.store_name) nomes.set(p.id, p.store_name);
      for (const m of (equipe ?? []) as Array<{ user_id: string; full_name: string | null }>) if (m.full_name) nomes.set(m.user_id, m.full_name);
    }
    const pedido = pedidoR.data as { number?: number | null } | null;
    return {
      nota: notaParaTela(nota, { pedidoNumero: pedido?.number ?? null }),
      eventos: eventos.map((evento) => ({ ...evento, atorNome: evento.ator ? nomes.get(evento.ator) ?? null : null })),
    };
  });
}

/** Descarta prévia ou nota que não foi autorizada. */
export async function DELETE(_req: Request, { params }: Contexto) {
  const { id } = await params;
  return rotaFiscal("fiscal.emitir", async ({ admin, empresaId, user }) => {
    const nota = await descartarPrevia(admin, { empresaId, notaId: exigirUuid(id, "Nota"), usuarioId: user.id });
    return { nota: notaParaTela(nota) };
  });
}
