import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { getOrderDetail, canViewOrders } from "@/lib/order-feed";

/**
 * GET /api/orders/[entityKey] — one order, its lifecycle, settlement siblings
 * and any linked ledger transactions.
 *
 * Keyed on entity_key (text) rather than entity_id: entity_id is BIGINT and
 * would break JSON.stringify, and the key is stable, unique and readable.
 * All 8,147 order keys are URL-safe today, but nothing enforces that, so the
 * client encodes and we decode.
 */
export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ entityKey: string }> }
) {
  const user = await getCurrentUser(req);
  if (!user) return NextResponse.json({ error: "unauthorized" }, { status: 403 });
  if (!canViewOrders(user.id)) {
    return NextResponse.json({ error: "forbidden" }, { status: 403 });
  }

  const { entityKey } = await params;
  const order = await getOrderDetail(decodeURIComponent(entityKey));
  if (!order) return NextResponse.json({ error: "not found" }, { status: 404 });

  return NextResponse.json(order);
}
