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

import { serializeWarehouse } from "@/features/warehouses/lib/serialize-warehouse";
import { warehouseInputSchema } from "@/features/warehouses/schemas/warehouse.schema";
import { createAuditTrailSafe } from "@/lib/audit-trail";
import { resolveMasterCode } from "@/lib/master-code";
import { prisma } from "@/lib/prisma";
import { requireApiAccess } from "@/lib/authorization";

export async function GET(request: Request) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;
  const data = await prisma.warehouse.findMany({ orderBy: [{ createdAt: "desc" }] });
  return NextResponse.json({ data: data.map(serializeWarehouse) });
}

export async function POST(request: Request) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;
  const parsed = warehouseInputSchema.safeParse(await request.json());
  if (!parsed.success) {
    return NextResponse.json({ message: "Validasi gagal", errors: parsed.error.flatten().fieldErrors }, { status: 400 });
  }
  try {
    const resolvedCode = await resolveMasterCode({
      role: auth.user.role,
      prefix: "WHS",
      requestedCode: parsed.data.code,
      countExisting: () =>
        prisma.warehouse.count({ where: { code: { startsWith: "WHS" } } }),
      exists: async (code) =>
        (await prisma.warehouse.count({ where: { code } })) > 0
    });
    if (!resolvedCode.ok) {
      return NextResponse.json({ message: "Validasi gagal", errors: { code: [resolvedCode.message] } }, { status: 400 });
    }
    const warehouse = await prisma.warehouse.create({
      data: {
        code: resolvedCode.code,
        name: parsed.data.name,
        address: parsed.data.address || null,
        status: parsed.data.status
      }
    });
    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "WAREHOUSE_CREATED",
      entityType: "WAREHOUSE",
      entityId: warehouse.id,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 201,
      summary: `Warehouse ${warehouse.code} dibuat`
    });
    return NextResponse.json({ data: serializeWarehouse(warehouse) }, { status: 201 });
  } catch (error) {
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2002") {
      return NextResponse.json({ message: "Validasi gagal", errors: { code: ["Kode gudang sudah dipakai"] } }, { status: 409 });
    }
    throw error;
  }
}
