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 { 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 item = await prisma.washingPlace.findUnique({
    where: { id: parsedId },
    include: {
      contactPeople: {
        orderBy: [{ createdAt: "asc" }, { id: "asc" }]
      }
    }
  });
  if (!item) return NextResponse.json({ message: "Washing place not found" }, { status: 404 });

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

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 = washingPlaceInputSchema.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.washingPlace.findUnique({
      where: { id: parsedId },
      include: {
        contactPeople: {
          orderBy: [{ createdAt: "asc" }, { id: "asc" }]
        }
      }
    });
    if (!existing) return NextResponse.json({ message: "Washing place not found" }, { status: 404 });

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

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

    const item = await prisma.washingPlace.update({
      where: { id: parsedId },
      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: {
          deleteMany: {},
          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_UPDATED",
      entityType: "WASHING_PLACE",
      entityId: item.id,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 200,
      summary: `Washing place ${item.code} diubah`,
      metadata: buildAuditChangeMetadata(
        {
          code: existing.code,
          name: existing.name,
          address: existing.address,
          phone: existing.phone,
          website: existing.website,
          email: existing.email,
          contact_people: existing.contactPeople.map((contact) => ({
            name: contact.name,
            mobile_phone: contact.mobilePhone,
            email: contact.email
          })),
          status: existing.status
        },
        {
          code: item.code,
          name: item.name,
          address: item.address,
          phone: item.phone,
          website: item.website,
          email: item.email,
          contact_people: item.contactPeople.map((contact) => ({
            name: contact.name,
            mobile_phone: contact.mobilePhone,
            email: contact.email
          })),
          status: item.status
        }
      )
    });

    return NextResponse.json({ data: serializeWashingPlace(item) });
  } catch (error) {
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2025") {
      return NextResponse.json({ message: "Washing place not found" }, { status: 404 });
    }
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2002") {
      return NextResponse.json(
        { message: "Validasi gagal", errors: { code: ["Kode tempat cuci 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.washingPlace.findUnique({ where: { id: parsedId } });
    await prisma.washingPlace.delete({ where: { id: parsedId } });

    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "WASHING_PLACE_DELETED",
      entityType: "WASHING_PLACE",
      entityId: parsedId,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 200,
      summary: `Washing place ${existing?.code ?? parsedId.toString()} dihapus`
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2025") {
      return NextResponse.json({ message: "Washing place not found" }, { status: 404 });
    }
    throw error;
  }
}

