import { NextRequest, NextResponse } from "next/server";
import { requestPasswordReset } from "@/lib/auth";

export async function POST(req: NextRequest) {
  let body: { email?: string };

  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid request body." }, { status: 400 });
  }

  const email = typeof body?.email === "string" ? body.email.trim().toLowerCase() : "";

  if (!email) {
    return NextResponse.json({ error: "Email is required." }, { status: 400 });
  }

  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:4000";

  try {
    const result = await requestPasswordReset({
      email,
      redirectTo: `${siteUrl}/reset-password`,
    });

    if (result.error) {
      console.error("[auth/forgot-password] Neon Auth error:", result.error);
    }

    // Always return success to prevent email enumeration
    return NextResponse.json({ success: true });
  } catch (err) {
    console.error("[auth/forgot-password] Unexpected error:", err);
    return NextResponse.json({ success: true });
  }
}
