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

import { serializeProfitShareScheme } from "@/features/profit-share-schemes/lib/serialize-profit-share-scheme";
import { profitShareSchemeInputSchema } from "@/features/profit-share-schemes/schemas/profit-share-scheme.schema";
import { createAuditTrailSafe } from "@/lib/audit-trail";
import { buildAuditChangeMetadata } from "@/lib/audit-trail-diff";
import { requireApiAccess } from "@/lib/authorization";
import { resolveMasterCode } from "@/lib/master-code";
import { prisma } from "@/lib/prisma";

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 scheme = await prisma.profitShareScheme.findUnique({ where: { id: parsedId } });
  if (!scheme) return NextResponse.json({ message: "Profit share scheme not found" }, { status: 404 });
  return NextResponse.json({ data: serializeProfitShareScheme(scheme) });
}

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 = profitShareSchemeInputSchema.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.profitShareScheme.findUnique({ where: { id: parsedId } });
    if (!existing) return NextResponse.json({ message: "Profit share scheme not found" }, { status: 404 });

    const resolvedCode = await resolveMasterCode({
      role: auth.user.role,
      prefix: "PSS",
      requestedCode: parsed.data.code,
      existingCode: existing.code,
      countExisting: () => prisma.profitShareScheme.count({ where: { code: { startsWith: "PSS" } } }),
      exists: async (code) =>
        (await prisma.profitShareScheme.count({ where: { code, id: { not: parsedId } } })) > 0
    });

    if (!resolvedCode.ok) {
      return NextResponse.json(
        { message: "Validasi gagal", errors: { code: [resolvedCode.message] } },
        { status: 400 }
      );
    }

    const scheme = await prisma.profitShareScheme.update({
      where: { id: parsedId },
      data: {
        code: resolvedCode.code,
        name: parsed.data.name,
        shareAgent: parsed.data.share_agent,
        shareCompany: parsed.data.share_company,
        status: parsed.data.status
      }
    });

    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "PROFIT_SHARE_SCHEME_UPDATED",
      entityType: "PROFIT_SHARE_SCHEME",
      entityId: scheme.id,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 200,
      summary: `Profit share scheme ${scheme.code} diubah`,
      metadata: buildAuditChangeMetadata(
        {
          code: existing.code,
          name: existing.name,
          share_agent: Number(existing.shareAgent),
          share_company: Number(existing.shareCompany),
          status: existing.status
        },
        {
          code: scheme.code,
          name: scheme.name,
          share_agent: Number(scheme.shareAgent),
          share_company: Number(scheme.shareCompany),
          status: scheme.status
        }
      )
    });

    return NextResponse.json({ data: serializeProfitShareScheme(scheme) });
  } catch (error) {
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2025") {
      return NextResponse.json({ message: "Profit share scheme not found" }, { status: 404 });
    }
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2002") {
      return NextResponse.json(
        { message: "Validasi gagal", errors: { code: ["Kode skema 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.profitShareScheme.findUnique({ where: { id: parsedId } });
    await prisma.profitShareScheme.delete({ where: { id: parsedId } });
    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "PROFIT_SHARE_SCHEME_DELETED",
      entityType: "PROFIT_SHARE_SCHEME",
      entityId: parsedId,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 200,
      summary: `Profit share scheme ${existing?.code ?? parsedId.toString()} dihapus`
    });
    return NextResponse.json({ success: true });
  } catch (error) {
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2025") {
      return NextResponse.json({ message: "Profit share scheme not found" }, { status: 404 });
    }
    throw error;
  }
}
