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 },
    include: {
      _count: {
        select: {
          receipts: true,
          lots: true
        }
      },
      lines: true
    }
  });

  if (!purchase) return NextResponse.json({ message: "Purchase not found" }, { status: 404 });

  if (purchase._count.receipts > 0 || purchase._count.lots > 0) {
    return NextResponse.json(
      { message: "Purchase sudah diterima dan memiliki receipt/lot." },
      { status: 409 }
    );
  }

  if (!purchase.receivedByEmployeeId) {
    return NextResponse.json({ message: "Penerima belum dipilih" }, { status: 400 });
  }

  if (!purchase.receivedAt) {
    return NextResponse.json({ message: "Waktu diterima belum diisi" }, { status: 400 });
  }

  const enteredQtyLines = purchase.lines.filter((line) => Number(line.qtyAccepted.toNumber()) > 0);
  if (enteredQtyLines.length === 0) {
    return NextResponse.json(
      { message: "Tidak ada baris dengan qty yang masuk > 0 untuk diajukan" },
      { status: 400 }
    );
  }

  if (purchase.status === "SUBMITTED") {
    return NextResponse.json({
      success: true,
      status: purchase.status,
      message: "Purchase sudah diajukan dan menunggu penerimaan."
    });
  }

  const updated = await prisma.purchase.update({
    where: { id: parsedId },
    data: { status: "SUBMITTED" }
  });

  await createAuditTrailSafe({
    userId: auth.user.id,
    action: "PURCHASE_SUBMITTED",
    entityType: "PURCHASE",
    entityId: updated.id,
    method: request.method,
    pathname: new URL(request.url).pathname,
    statusCode: 200,
    summary: `Purchase ${updated.purchaseNo} diajukan untuk penerimaan`,
    metadata: buildAuditChangeMetadata(
      { status: purchase.status },
      { status: updated.status }
    )
  });

  return NextResponse.json({
    success: true,
    status: updated.status,
    message: "Purchase diajukan. Buat receipt dan lot dari menu Penerimaan."
  });
}
