import { cookies } from "next/headers";
import { NextResponse } from "next/server";

import { gatewayFetch } from "@/lib/api/gateway";
import { ACCESS_TOKEN_COOKIE } from "@/lib/auth/constants";

export const dynamic = "force-dynamic";

/**
 * Update the signed-in user's profile via Identity (`PATCH /v1/users/me`).
 * Currently surfaces the display name (full_name); the Identity DTO accepts more
 * fields that can be added here as the settings UI grows.
 */
export async function PATCH(req: Request) {
  const token = (await cookies()).get(ACCESS_TOKEN_COOKIE)?.value;
  if (!token) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await req.json().catch(() => null);
  const fullName = typeof body?.full_name === "string" ? body.full_name.trim() : undefined;
  if (fullName === undefined) {
    return NextResponse.json({ error: "Nothing to update" }, { status: 400 });
  }

  const res = await gatewayFetch("/v1/users/me", {
    method: "PATCH",
    headers: { Authorization: `Bearer ${token}` },
    body: JSON.stringify({ full_name: fullName }),
  });

  if (!res.ok) {
    const data = await res.json().catch(() => null);
    return NextResponse.json(
      { error: data?.message ?? "Could not update profile." },
      { status: res.status }
    );
  }

  const user = await res.json().catch(() => null);
  return NextResponse.json({ user });
}
