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

import { serializeUnit } from "@/features/units/lib/serialize-unit";
import { unitInputSchema } from "@/features/units/schemas/unit.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.unit.findMany({ orderBy: [{ createdAt: "desc" }] });
  return NextResponse.json({ data: data.map(serializeUnit) });
}

export async function POST(request: Request) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;
  const parsed = unitInputSchema.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: "UNT",
      requestedCode: parsed.data.code,
      countExisting: () =>
        prisma.unit.count({ where: { code: { startsWith: "UNT" } } }),
      exists: async (code) =>
        (await prisma.unit.count({ where: { code } })) > 0
    });
    if (!resolvedCode.ok) {
      return NextResponse.json(
        { message: "Validasi gagal", errors: { code: [resolvedCode.message] } },
        { status: 400 }
      );
    }
    const unit = await prisma.unit.create({
      data: {
        code: resolvedCode.code,
        name: parsed.data.name
      }
    });
    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "UNIT_CREATED",
      entityType: "UNIT",
      entityId: unit.id,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 201,
      summary: `Unit ${unit.code} dibuat`
    });
    return NextResponse.json({ data: serializeUnit(unit) }, { status: 201 });
  } catch (error) {
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2002") {
      return NextResponse.json(
        { message: "Validasi gagal", errors: { code: ["Kode unit sudah dipakai"] } },
        { status: 409 }
      );
    }
    throw error;
  }
}
