import { NextResponse } from "next/server";
import { abrirEstoque, UUID } from "@/lib/estoque/servidor";
import type { BaixaDoItem } from "@/lib/estoque/tipos";

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

/* O que cada item do pedido tirou (e devolveu) do estoque
   (estoque_do_item_do_pedido). Empresa fora do v2 responde { v2: false }. */
export async function GET(_req: Request, { params }: Params) {
  const r = await abrirEstoque(["orders.read", "products.stock.read"]);
  if (!r.ok) return r.resposta;
  if (!r.e.v2) return NextResponse.json({ v2: false, itens: [] });
  const { id } = await params;
  if (!UUID.test(id)) return NextResponse.json({ error: "Pedido não encontrado." }, { status: 404 });
  const { data: pedido } = await r.e.admin.from("orders").select("id").eq("id", id).in("user_id", r.e.ids).maybeSingle();
  if (!pedido) return NextResponse.json({ error: "Pedido não encontrado." }, { status: 404 });

  const { data: itens } = await r.e.admin.from("order_items").select("id,title,quantity,product_id").eq("order_id", id).limit(300);
  const lista = (itens as Array<{ id: string; title: string | null; quantity: number | null; product_id: string | null }> | null) ?? [];
  const resultado = await Promise.all(
    lista.map(async (it) => {
      const { data, error } = await r.e.supabase.rpc("estoque_do_item_do_pedido", { p_item_pedido: it.id });
      return {
        item_pedido_id: it.id,
        titulo: it.title,
        quantidade: Number(it.quantity) || 0,
        produto_id: it.product_id,
        baixas: error ? [] : ((data as BaixaDoItem[] | null) ?? []),
        erro: error?.message ?? null,
      };
    })
  );
  return NextResponse.json({ v2: true, itens: resultado });
}
