import { NextResponse } from "next/server";

import { requireSuperAdmin } from "@/lib/authorization";
import { updateAdminTableRow } from "@/services/admin-tables.service";

export const dynamic = "force-dynamic";

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

export async function PATCH(request: Request, { params }: Context) {
  const auth = await requireSuperAdmin(request);
  if (!auth.ok) return auth.response;

  const { table, id } = await params;
  try {
    const body = (await request.json()) as unknown;
    if (!body || typeof body !== "object" || Array.isArray(body)) {
      return NextResponse.json(
        { message: "Corps JSON invalide" },
        { status: 400 },
      );
    }
    const result = await updateAdminTableRow(
      table,
      id,
      body as Record<string, unknown>,
    );
    if (!result.updated) {
      return NextResponse.json(
        { message: "Ligne introuvable" },
        { status: 404 },
      );
    }
    return NextResponse.json(result);
  } catch (reason) {
    const message =
      reason instanceof Error ? reason.message : "Modification impossible";
    const status =
      message === "TABLE_NOT_FOUND"
        ? 404
        : message === "PROTECTED_TABLE"
          ? 403
          : 400;
    return NextResponse.json({ message }, { status });
  }
}
