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

import { serializeCourier } from "@/features/couriers/lib/serialize-courier";
import { courierInputSchema } from "@/features/couriers/schemas/courier.schema";
import { createAuditTrailSafe } from "@/lib/audit-trail";
import { requireApiAccess } from "@/lib/authorization";
import { resolveMasterCode } from "@/lib/master-code";
import { prisma } from "@/lib/prisma";

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

  const items = await prisma.courier.findMany({
    orderBy: [{ createdAt: "desc" }]
  });

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

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

  const parsed = courierInputSchema.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: "CUR",
      requestedCode: parsed.data.code,
      countExisting: () => prisma.courier.count({ where: { code: { startsWith: "CUR" } } }),
      exists: async (code) => (await prisma.courier.count({ where: { code } })) > 0
    });

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

    const item = await prisma.courier.create({
      data: {
        code: resolvedCode.code,
        name: parsed.data.name,
        address: parsed.data.address || null,
        phone: parsed.data.phone || null,
        website: parsed.data.website || null,
        email: parsed.data.email || null,
        status: parsed.data.status
      }
    });

    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "COURIER_CREATED",
      entityType: "COURIER",
      entityId: item.id,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 201,
      summary: `Kurir ${item.code} dibuat`
    });

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

