import { NextResponse } from "next/server";

import { createAuditTrailSafe } from "@/lib/audit-trail";
import { buildAuditChangeMetadata } from "@/lib/audit-trail-diff";
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 POST(request: Request, context: RouteContext) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;

  const parsedId = parseId((await context.params).id);
  if (parsedId === null) return NextResponse.json({ message: "Invalid id" }, { status: 400 });
  const purchase = await prisma.purchase.findUnique({ where: { id: parsedId } });
  if (!purchase) return NextResponse.json({ message: "Purchase not found" }, { status: 404 });
  const updated = await prisma.purchase.update({
    where: { id: parsedId },
    data: { status: "CANCELLED" }
  });
  await createAuditTrailSafe({
    userId: auth.user.id,
    action: "PURCHASE_CANCELLED",
    entityType: "PURCHASE",
    entityId: updated.id,
    method: request.method,
    pathname: new URL(request.url).pathname,
    statusCode: 200,
    summary: `Purchase ${updated.purchaseNo} dibatalkan`,
    metadata: buildAuditChangeMetadata(
      { status: purchase.status },
      { status: updated.status }
    )
  });
  return NextResponse.json({ success: true, status: updated.status });
}
