import { NextResponse } from "next/server";

import { ensureFixedUnits, getFixedUnitLockMessage } from "@/features/units/lib/fixed-units";
import { serializeUnit } from "@/features/units/lib/serialize-unit";
import { requireApiAccess } from "@/lib/authorization";
import { prisma } from "@/lib/prisma";

type RouteContext = { params: Promise<{ id: string }> };
const parseId = (id: string) => { try { return BigInt(id); } catch { return null; } };

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

  const parsedId = parseId((await context.params).id);
  if (parsedId === null) return NextResponse.json({ message: "Invalid id" }, { status: 400 });
  const unit = await prisma.unit.findUnique({ where: { id: parsedId } });
  if (!unit) return NextResponse.json({ message: "Unit not found" }, { status: 404 });
  return NextResponse.json({ data: serializeUnit(unit) });
}

export async function PUT(request: Request, context: RouteContext) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;
  void context;
  return NextResponse.json({ message: getFixedUnitLockMessage() }, { status: 403 });
}

export async function DELETE(request: Request, context: RouteContext) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;
  void context;
  return NextResponse.json({ message: getFixedUnitLockMessage() }, { status: 403 });
}
