import { NextResponse } from "next/server";

import { getDiplomeDetails, updateDiplomeFeed, deleteDiplomeFeed } from "../../../../server/diplomes.server";
import { requireAuth } from "../../../../lib/requireAuth";
import { diplomeUpdateSchema } from "../../../../validators/diplomes";

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 data = await getDiplomeDetails(id);

  if (!data.diplome) {
    return NextResponse.json(
      { message: "Diplome not found" },
      { status: 404 },
    );
  }

  return NextResponse.json({
    message: "Diplome retrieved successfully",
    ...data,
  });
}

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 = diplomeUpdateSchema.safeParse(body);

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

  const data = await updateDiplomeFeed(id, parsed.data);

  if (!data.diplome) {
    return NextResponse.json(
      { message: "Diplome not found" },
      { status: 404 },
    );
  }

  return NextResponse.json({
    message: "Diplome updated successfully",
    ...data,
  });
}

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 data;

  try {
    data = await deleteDiplomeFeed(id);
  } catch {
    return NextResponse.json(
      { message: "Internal Server Error" },
      { status: 500 },
    );
  }

  if (!data.diplome) {
    return NextResponse.json(
      { message: "Diplome not found" },
      { status: 404 },
    );
  }

  return NextResponse.json({
    message: "Diplome deleted successfully",
    ...data,
  });
}
