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

import { serializeBank } from "@/features/banks/lib/serialize-bank";
import { bankInputSchema } from "@/features/banks/schemas/bank.schema";
import { createAuditTrailSafe } from "@/lib/audit-trail";
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 banks = await prisma.bank.findMany({
    orderBy: [{ status: "asc" }, { code: "asc" }]
  });

  return NextResponse.json({
    data: banks.map(serializeBank)
  });
}

export async function POST(request: Request) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;

  const parsed = bankInputSchema.safeParse(await request.json());
  if (!parsed.success) {
    return NextResponse.json(
      { message: "Validasi gagal", errors: parsed.error.flatten().fieldErrors },
      { status: 400 }
    );
  }

  try {
    const bank = await prisma.bank.create({
      data: {
        code: parsed.data.code,
        name: parsed.data.name,
        address: parsed.data.address || null,
        status: parsed.data.status
      }
    });

    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "BANK_CREATED",
      entityType: "BANK",
      entityId: bank.id,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 201,
      summary: `Bank ${bank.code} dibuat`
    });

    return NextResponse.json({ data: serializeBank(bank) }, { status: 201 });
  } catch (error) {
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2002") {
      return NextResponse.json(
        {
          message: "Validasi gagal",
          errors: {
            code: ["Kode atau nama bank sudah dipakai"]
          }
        },
        { status: 409 }
      );
    }
    throw error;
  }
}
