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 { 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.adjustmentReason.findMany({ orderBy: [{ createdAt: "desc" }] });
  return NextResponse.json({ data: data.map(serializeAdjustmentReason) });
}

export async function POST(request: Request) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;
  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 resolvedCode = await resolveMasterCode({
      role: auth.user.role,
      prefix: "ADJ",
      requestedCode: parsed.data.code,
      countExisting: () =>
        prisma.adjustmentReason.count({ where: { code: { startsWith: "ADJ" } } }),
      exists: async (code) =>
        (await prisma.adjustmentReason.count({ where: { code } })) > 0
    });
    if (!resolvedCode.ok) {
      return NextResponse.json(
        { message: "Validasi gagal", errors: { code: [resolvedCode.message] } },
        { status: 400 }
      );
    }
    const reason = await prisma.adjustmentReason.create({
      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_CREATED",
      entityType: "ADJUSTMENT_REASON",
      entityId: reason.id,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 201,
      summary: `Adjustment reason ${reason.code} dibuat`
    });
    return NextResponse.json({ data: serializeAdjustmentReason(reason) }, { status: 201 });
  } catch (error) {
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2002") {
      return NextResponse.json(
        { message: "Validasi gagal", errors: { code: ["Kode alasan sudah dipakai"] } },
        { status: 409 }
      );
    }
    throw error;
  }
}
