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

/**
 * Change the signed-in user's password via Identity (`/v1/auth/password/change`).
 * Identity re-validates the current password server-side, so no client-side
 * re-authentication round-trip is needed.
 */
export async function POST(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 currentPassword = body?.current_password;
  const newPassword = body?.new_password;
  if (!currentPassword || !newPassword) {
    return NextResponse.json(
      { error: "Current and new password are required." },
      { status: 400 }
    );
  }
  if (typeof newPassword !== "string" || newPassword.length < 8) {
    return NextResponse.json(
      { error: "New password must be at least 8 characters." },
      { status: 400 }
    );
  }

  const res = await gatewayFetch("/v1/auth/password/change", {
    method: "POST",
    headers: { Authorization: `Bearer ${token}` },
    body: JSON.stringify({
      current_password: currentPassword,
      new_password: newPassword,
    }),
  });

  if (!res.ok) {
    const data = await res.json().catch(() => null);
    const message =
      res.status === 400 || res.status === 401
        ? (data?.message ?? "Current password is incorrect.")
        : (data?.message ?? "Could not change password.");
    return NextResponse.json({ error: message }, { status: res.status });
  }

  return NextResponse.json({ ok: true });
}
