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

// Profile fields the user may edit; forwarded as-is (snake_case) to the Identity
// PATCH DTO. This is the data-collection surface that later powers AI video gen.
const EDITABLE_FIELDS = [
  "full_name",
  "slogan",
  "about_me",
  "company_name",
  "website_name",
  "birth_date",
  "gender",
  "country_code",
  "national_code",
  "method_of_introduction",
] as const;

/**
 * Update the signed-in user's profile via Identity (`PATCH /v1/users/me`).
 * Forwards any of the editable profile fields that are present in the request body.
 */
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 payload: Record<string, unknown> = {};
  for (const key of EDITABLE_FIELDS) {
    const v = body?.[key];
    if (v === undefined || v === null) continue;
    payload[key] = typeof v === "string" ? v.trim() : v;
  }
  if (Object.keys(payload).length === 0) {
    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(payload),
  });

  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 });
}
