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

interface ForgotPasswordBody {
  email: string;
}

export async function POST(req: NextRequest) {
  let body: ForgotPasswordBody;

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

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

  if (!trimmedEmail) {
    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: trimmedEmail,
      redirectTo: `${siteUrl}/reset-password`,
    });

    if (result.error) {
      console.error("[auth/forgot-password] Request failed:", result.error);
      // Don't reveal whether the email exists or not for security
      return NextResponse.json({ success: true });
    }

    console.log("[auth/forgot-password] Reset email sent to:", trimmedEmail);
    // Always return success to prevent email enumeration
    return NextResponse.json({ success: true });
  } catch (err) {
    console.error("[auth/forgot-password] Unexpected error:", err);
    // Don't reveal error details to the client
    return NextResponse.json({ success: true });
  }
}
