import { NextResponse } from "next/server";
import { gatewayFetch } from "@/lib/api/gateway";

export const dynamic = "force-dynamic";

/** POST /api/auth/password-reset-confirm — confirm reset with OTP + new password */
export async function POST(request: Request) {
  let body: unknown;
  try { body = await request.json(); } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }
  const { email, otp, new_password } = body as { email?: string; otp?: string; new_password?: string };
  if (!email || !otp || !new_password) {
    return NextResponse.json({ error: "email, otp, and new_password are required" }, { status: 400 });
  }

  const res = await gatewayFetch("/v1/auth/password/reset/confirm", {
    method: "POST",
    body: JSON.stringify({ email, otp, new_password }),
  });
  const data = await res.json().catch(() => null) as { message?: string } | null;
  if (!res.ok) {
    return NextResponse.json(
      { error: data?.message ?? "Invalid or expired code" },
      { status: res.status }
    );
  }
  return NextResponse.json({ ok: true });
}
