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

import { serializeWarehouseLocation } from "@/features/warehouse-locations/lib/serialize-warehouse-location";
import { warehouseLocationInputSchema } from "@/features/warehouse-locations/schemas/warehouse-location.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 location = await prisma.warehouseLocation.findUnique({
    where: { id: parsedId },
    include: { warehouse: { select: { name: true } } }
  });
  if (!location) return NextResponse.json({ message: "Warehouse location not found" }, { status: 404 });
  return NextResponse.json({ data: serializeWarehouseLocation(location) });
}

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 = warehouseLocationInputSchema.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.warehouseLocation.findUnique({ where: { id: parsedId } });
    if (!existing) return NextResponse.json({ message: "Warehouse location not found" }, { status: 404 });
    const resolvedCode = await resolveMasterCode({
      role: auth.user.role,
      prefix: "LOC",
      requestedCode: parsed.data.code,
      existingCode: existing.code,
      countExisting: () =>
        prisma.warehouseLocation.count({ where: { code: { startsWith: "LOC" } } }),
      exists: async (code) =>
        (await prisma.warehouseLocation.count({ where: { code, id: { not: parsedId } } })) > 0
    });
    if (!resolvedCode.ok) {
      return NextResponse.json(
        { message: "Validasi gagal", errors: { code: [resolvedCode.message] } },
        { status: 400 }
      );
    }
    const location = await prisma.warehouseLocation.update({
      where: { id: parsedId },
      data: {
        warehouseId: BigInt(parsed.data.warehouse_id),
        code: resolvedCode.code,
        name: parsed.data.name,
        locationType: parsed.data.location_type || null,
        status: parsed.data.status
      },
      include: { warehouse: { select: { name: true } } }
    });
    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "WAREHOUSE_LOCATION_UPDATED",
      entityType: "WAREHOUSE_LOCATION",
      entityId: location.id,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 200,
      summary: `Warehouse location ${location.code} diubah`,
      metadata: buildAuditChangeMetadata(
        {
          warehouse_id: existing.warehouseId,
          code: existing.code,
          name: existing.name,
          location_type: existing.locationType,
          status: existing.status
        },
        {
          warehouse_id: location.warehouseId,
          code: location.code,
          name: location.name,
          location_type: location.locationType,
          status: location.status
        }
      )
    });
    return NextResponse.json({ data: serializeWarehouseLocation(location) });
  } catch (error) {
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2025") {
      return NextResponse.json({ message: "Warehouse location not found" }, { status: 404 });
    }
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2002") {
      return NextResponse.json(
        { message: "Validasi gagal", errors: { code: ["Kode lokasi sudah dipakai di gudang ini"] } },
        { status: 409 }
      );
    }
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2003") {
      return NextResponse.json(
        { message: "Validasi gagal", errors: { warehouse_id: ["Gudang tidak valid"] } },
        { status: 400 }
      );
    }
    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.warehouseLocation.findUnique({ where: { id: parsedId } });
    await prisma.warehouseLocation.delete({ where: { id: parsedId } });
    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "WAREHOUSE_LOCATION_DELETED",
      entityType: "WAREHOUSE_LOCATION",
      entityId: parsedId,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 200,
      summary: `Warehouse location ${existing?.code ?? parsedId.toString()} dihapus`
    });
    return NextResponse.json({ success: true });
  } catch (error) {
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2025") {
      return NextResponse.json({ message: "Warehouse location not found" }, { status: 404 });
    }
    throw error;
  }
}
