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

import { serializeCurrency } from "@/features/currencies/lib/serialize-currency";
import { currencyInputSchema } from "@/features/currencies/schemas/currency.schema";
import { createAuditTrailSafe } from "@/lib/audit-trail";
import { buildAuditChangeMetadata } from "@/lib/audit-trail-diff";
import { prisma } from "@/lib/prisma";
import { requireApiAccess } from "@/lib/authorization";

type RouteContext = { params: Promise<{ id: string }> };

const parseId = (id: string) => {
  try {
    return BigInt(id);
  } catch {
    return null;
  }
};

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

  const parsedId = parseId((await context.params).id);
  if (parsedId === null) return NextResponse.json({ message: "Invalid id" }, { status: 400 });

  const currency = await prisma.currency.findUnique({ where: { id: parsedId } });
  if (!currency) return NextResponse.json({ message: "Currency not found" }, { status: 404 });

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

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

  const parsedId = parseId((await context.params).id);
  if (parsedId === null) return NextResponse.json({ message: "Invalid id" }, { status: 400 });

  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 existing = await prisma.currency.findUnique({ where: { id: parsedId } });
    if (!existing) return NextResponse.json({ message: "Currency not found" }, { status: 404 });

    const currency = await prisma.currency.update({
      where: { id: parsedId },
      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_UPDATED",
      entityType: "CURRENCY",
      entityId: currency.id,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 200,
      summary: `Currency ${currency.code} diubah`,
      metadata: buildAuditChangeMetadata(
        {
          code: existing.code,
          name: existing.name,
          description: existing.description,
          status: existing.status
        },
        {
          code: currency.code,
          name: currency.name,
          description: currency.description,
          status: currency.status
        }
      )
    });

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

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

  const parsedId = parseId((await context.params).id);
  if (parsedId === null) return NextResponse.json({ message: "Invalid id" }, { status: 400 });

  try {
    const existing = await prisma.currency.findUnique({ where: { id: parsedId } });
    if (!existing) return NextResponse.json({ message: "Currency not found" }, { status: 404 });

    const settingsUsingCurrency = await prisma.appSetting.count({
      where: { currencyCode: existing.code }
    });
    if (settingsUsingCurrency > 0) {
      return NextResponse.json(
        { message: "Currency sedang dipakai di pengaturan sistem dan tidak bisa dihapus." },
        { status: 409 }
      );
    }

    await prisma.currency.delete({ where: { id: parsedId } });

    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "CURRENCY_DELETED",
      entityType: "CURRENCY",
      entityId: parsedId,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 200,
      summary: `Currency ${existing.code} dihapus`
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2025") {
      return NextResponse.json({ message: "Currency not found" }, { status: 404 });
    }
    throw error;
  }
}
