import { NextResponse } from "next/server";

import {
  deleteClassification,
  getClassificationById,
  updateClassification,
} from "@/services/reference-lookups.service";
import { requireAuth } from "@/lib/requireAuth";
import { classificationUpdateSchema } from "@/validators/reference-lookups";

type RouteContext = {
  params: Promise<{
    id: string;
  }>;
};

function parseId(idParam: string) {
  const id = Number(idParam);

  if (!Number.isInteger(id)) {
    return null;
  }

  return id;
}

export async function GET(_request: Request, { params }: RouteContext) {
  const authError = requireAuth(_request);

  if (authError) {
    return authError;
  }

  const { id: idParam } = await params;
  const id = parseId(idParam);

  if (id === null) {
    return NextResponse.json({ message: "Invalid id parameter" }, { status: 400 });
  }

  const classification = await getClassificationById(id);

  if (!classification) {
    return NextResponse.json({ message: "Classification not found" }, { status: 404 });
  }

  return NextResponse.json({
    message: "Classification retrieved successfully",
    classification,
  });
}

export async function PUT(request: Request, { params }: RouteContext) {
  const authError = requireAuth(request);

  if (authError) {
    return authError;
  }

  const { id: idParam } = await params;
  const id = parseId(idParam);

  if (id === null) {
    return NextResponse.json({ message: "Invalid id parameter" }, { status: 400 });
  }

  let body: unknown;

  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ message: "Invalid JSON body" }, { status: 400 });
  }

  const parsed = classificationUpdateSchema.safeParse(body);

  if (!parsed.success) {
    return NextResponse.json(
      { message: "Invalid body parameters", issues: parsed.error.flatten() },
      { status: 400 },
    );
  }

  let classification;

  try {
    classification = await updateClassification(id, parsed.data);
  } catch {
    return NextResponse.json({ message: "Classification not found" }, { status: 404 });
  }

  return NextResponse.json({
    message: "Classification updated successfully",
    classification,
  });
}

export async function PATCH(request: Request, { params }: RouteContext) {
  const authError = requireAuth(request);

  if (authError) {
    return authError;
  }

  const { id: idParam } = await params;
  const id = parseId(idParam);

  if (id === null) {
    return NextResponse.json({ message: "Invalid id parameter" }, { status: 400 });
  }

  let body: unknown;

  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ message: "Invalid JSON body" }, { status: 400 });
  }

  const parsed = classificationUpdateSchema.safeParse(body);

  if (!parsed.success) {
    return NextResponse.json(
      { message: "Invalid body parameters", issues: parsed.error.flatten() },
      { status: 400 },
    );
  }

  let classification;

  try {
    classification = await updateClassification(id, parsed.data);
  } catch {
    return NextResponse.json({ message: "Classification not found" }, { status: 404 });
  }

  return NextResponse.json({
    message: "Classification patched successfully",
    classification,
  });
}

export async function DELETE(_request: Request, { params }: RouteContext) {
  const authError = requireAuth(_request);

  if (authError) {
    return authError;
  }

  const { id: idParam } = await params;
  const id = parseId(idParam);

  if (id === null) {
    return NextResponse.json({ message: "Invalid id parameter" }, { status: 400 });
  }

  let classification;

  try {
    classification = await deleteClassification(id);
  } catch {
    return NextResponse.json({ message: "Classification not found" }, { status: 404 });
  }

  return NextResponse.json({
    message: "Classification deleted successfully",
    classification,
  });
}
