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 { 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.profitShareScheme.findMany({ orderBy: [{ createdAt: "desc" }] });
  return NextResponse.json({ data: data.map(serializeProfitShareScheme) });
}

export async function POST(request: Request) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;
  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 resolvedCode = await resolveMasterCode({
      role: auth.user.role,
      prefix: "PSS",
      requestedCode: parsed.data.code,
      countExisting: () => prisma.profitShareScheme.count({ where: { code: { startsWith: "PSS" } } }),
      exists: async (code) => (await prisma.profitShareScheme.count({ where: { code } })) > 0
    });

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

    const scheme = await prisma.profitShareScheme.create({
      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_CREATED",
      entityType: "PROFIT_SHARE_SCHEME",
      entityId: scheme.id,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 201,
      summary: `Profit share scheme ${scheme.code} dibuat`
    });

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