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

import { serializeBuyer } from "@/features/buyers/lib/serialize-buyer";
import { buyerInputSchema } from "@/features/buyers/schemas/buyer.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 buyers = await prisma.buyer.findMany({
    include: {
      contactPeople: {
        orderBy: [{ createdAt: "asc" }, { id: "asc" }]
      }
    },
    orderBy: [{ createdAt: "desc" }]
  });

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

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

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

  try {
    if (parsed.data.bank_name) {
      const bank = await prisma.bank.findFirst({
        where: {
          name: parsed.data.bank_name,
          status: "ACTIVE"
        }
      });

      if (!bank) {
        return NextResponse.json(
          {
            message: "Validasi gagal",
            errors: {
              bank_name: ["Bank harus dipilih dari master bank aktif untuk buyer"]
            }
          },
          { status: 400 }
        );
      }
    }

    const resolvedCode = await resolveMasterCode({
      role: auth.user.role,
      prefix: "CUS",
      requestedCode: parsed.data.code,
      countExisting: () =>
        prisma.buyer.count({ where: { code: { startsWith: "CUS" } } }),
      exists: async (code) =>
        (await prisma.buyer.count({ where: { code } })) > 0
    });

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

    const buyer = await prisma.buyer.create({
      data: {
        code: resolvedCode.code,
        name: parsed.data.name,
        phone: parsed.data.phone || null,
        email: parsed.data.email || null,
        bankName: parsed.data.bank_name || null,
        bankAccountNumber: parsed.data.bank_account_number || null,
        address: parsed.data.address || null,
        contactPeople: {
          create: parsed.data.contact_people.map((contactPerson) => ({
            name: contactPerson.name,
            mobilePhone: contactPerson.mobile_phone || null,
            email: contactPerson.email || null
          }))
        },
        status: parsed.data.status
      },
      include: {
        contactPeople: {
          orderBy: [{ createdAt: "asc" }, { id: "asc" }]
        }
      }
    });
    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "CUSTOMER_CREATED",
      entityType: "CUSTOMER",
      entityId: buyer.id,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 201,
      summary: `Buyer ${buyer.code} dibuat`
    });

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

    throw error;
  }
}
