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

import { ensureDefaultCurrencies } from "@/features/currencies/lib/default-currencies";
import { serializeCurrency } from "@/features/currencies/lib/serialize-currency";
import { currencyInputSchema } from "@/features/currencies/schemas/currency.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;

  await ensureDefaultCurrencies();
  const data = await prisma.currency.findMany({
    orderBy: [{ status: "asc" }, { code: "asc" }]
  });

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

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

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

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

    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "CURRENCY_CREATED",
      entityType: "CURRENCY",
      entityId: currency.id,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 201,
      summary: `Currency ${currency.code} dibuat`
    });

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