import { NextResponse } from "next/server";

import { serializeLotTransformationDetail } from "@/features/lot-transformations/lib/serialize-transformation";
import { getLotTransformationById } from "@/features/lot-transformations/lib/transformation-query";
import { requireApiAccess } from "@/lib/authorization";

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

function parseBigInt(value: string) {
  try {
    return BigInt(value);
  } catch {
    return null;
  }
}

export async function GET(request: Request, context: RouteContext) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;

  const id = parseBigInt((await context.params).id);
  if (id === null) {
    return NextResponse.json({ message: "Invalid id" }, { status: 400 });
  }

  const item = await getLotTransformationById(id);
  if (!item) {
    return NextResponse.json({ message: "Transformation not found" }, { status: 404 });
  }

  return NextResponse.json({
    data: serializeLotTransformationDetail(item)
  });
}
