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

import { serializeEmployee } from "@/features/employees/lib/serialize-employee";
import { employeeInputSchema } from "@/features/employees/schemas/employee.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;

  try {
    const items = await prisma.employee.findMany({ orderBy: [{ createdAt: "desc" }] });
    return NextResponse.json({ data: items.map(serializeEmployee) });
  } catch (error) {
    const message =
      process.env.NODE_ENV === "development" && error instanceof Error ? error.message : "Internal server error";
    return NextResponse.json({ message }, { status: 500 });
  }
}

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

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

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

    const employee = await prisma.employee.create({
      data: {
        code: resolvedCode.code,
        name: parsed.data.name,
        email: parsed.data.email || null,
        mobile: parsed.data.mobile || null,
        position: parsed.data.position,
        address: parsed.data.address || null,
        status: parsed.data.status
      }
    });

    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "EMPLOYEE_CREATED",
      entityType: "EMPLOYEE",
      entityId: employee.id,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 201,
      summary: `Employee ${employee.code} dibuat`
    });

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