import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
import { NextResponse } from "next/server";

import { serializeAdjustmentReason } from "@/features/adjustment-reasons/lib/serialize-adjustment-reason";
import { adjustmentReasonInputSchema } from "@/features/adjustment-reasons/schemas/adjustment-reason.schema";
import { createAuditTrailSafe } from "@/lib/audit-trail";
import { buildAuditChangeMetadata } from "@/lib/audit-trail-diff";
import { requireApiAccess } from "@/lib/authorization";
import { resolveMasterCode } from "@/lib/master-code";
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;

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

export async function PUT(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 parsed = adjustmentReasonInputSchema.safeParse(await request.json());
  if (!parsed.success) {
    return NextResponse.json(
      { message: "Validasi gagal", errors: parsed.error.flatten().fieldErrors },
      { status: 400 }
    );
  }
  try {
    const existing = await prisma.adjustmentReason.findUnique({ where: { id: parsedId } });
    if (!existing) return NextResponse.json({ message: "Adjustment reason not found" }, { status: 404 });
    const resolvedCode = await resolveMasterCode({
      role: auth.user.role,
      prefix: "ADJ",
      requestedCode: parsed.data.code,
      existingCode: existing.code,
      countExisting: () =>
        prisma.adjustmentReason.count({ where: { code: { startsWith: "ADJ" } } }),
      exists: async (code) =>
        (await prisma.adjustmentReason.count({ where: { code, id: { not: parsedId } } })) > 0
    });
    if (!resolvedCode.ok) {
      return NextResponse.json(
        { message: "Validasi gagal", errors: { code: [resolvedCode.message] } },
        { status: 400 }
      );
    }
    const reason = await prisma.adjustmentReason.update({
      where: { id: parsedId },
      data: {
        code: resolvedCode.code,
        name: parsed.data.name,
        description: parsed.data.description || null,
        category: parsed.data.category,
        status: parsed.data.status
      }
    });
    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "ADJUSTMENT_REASON_UPDATED",
      entityType: "ADJUSTMENT_REASON",
      entityId: reason.id,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 200,
      summary: `Adjustment reason ${reason.code} diubah`,
      metadata: buildAuditChangeMetadata(
        {
          code: existing.code,
          name: existing.name,
          description: existing.description,
          category: existing.category,
          status: existing.status
        },
        {
          code: reason.code,
          name: reason.name,
          description: reason.description,
          category: reason.category,
          status: reason.status
        }
      )
    });
    return NextResponse.json({ data: serializeAdjustmentReason(reason) });
  } catch (error) {
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2025") {
      return NextResponse.json({ message: "Adjustment reason not found" }, { status: 404 });
    }
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2002") {
      return NextResponse.json(
        { message: "Validasi gagal", errors: { code: ["Kode alasan sudah dipakai"] } },
        { status: 409 }
      );
    }
    throw error;
  }
}

export async function DELETE(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 });
  try {
    const existing = await prisma.adjustmentReason.findUnique({ where: { id: parsedId } });
    await prisma.adjustmentReason.delete({ where: { id: parsedId } });
    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "ADJUSTMENT_REASON_DELETED",
      entityType: "ADJUSTMENT_REASON",
      entityId: parsedId,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 200,
      summary: `Adjustment reason ${existing?.code ?? parsedId.toString()} dihapus`
    });
    return NextResponse.json({ success: true });
  } catch (error) {
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2025") {
      return NextResponse.json({ message: "Adjustment reason not found" }, { status: 404 });
    }
    throw error;
  }
}
