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

import { serializeWashingPlace } from "@/features/washing-places/lib/serialize-washing-place";
import { washingPlaceInputSchema } from "@/features/washing-places/schemas/washing-place.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.washingPlace.findMany({
    include: {
      contactPeople: {
        orderBy: [{ createdAt: "asc" }, { id: "asc" }]
      }
    },
    orderBy: [{ createdAt: "desc" }]
  });

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

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

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

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

    const item = await prisma.washingPlace.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,
        contactPeople: {
          create: parsed.data.contact_people.map((contact) => ({
            name: contact.name,
            mobilePhone: contact.mobile_phone || null,
            email: contact.email || null
          }))
        },
        status: parsed.data.status
      },
      include: {
        contactPeople: {
          orderBy: [{ createdAt: "asc" }, { id: "asc" }]
        }
      }
    });

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

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

