import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import crypto from "crypto";
import { sendPasswordResetEmail } from "@/lib/email/send";
import { checkRateLimit, getClientIp, AUTH_RATE_LIMITS } from "@/lib/rate-limit";
import { logger } from "@/lib/logger";

/**
 * POST /api/auth/forgot-password
 *
 * Generates a password reset token and sends it via email.
 * Always returns 200 to prevent email enumeration.
 */
export async function POST(request: NextRequest) {
  try {
    // Rate limit
    const ip = getClientIp(request.headers);
    const limit = checkRateLimit(`forgot:${ip}`, AUTH_RATE_LIMITS.forgotPassword);
    if (!limit.allowed) {
      return NextResponse.json(
        { message: "Too many requests. Please try again later." },
        { status: 429, headers: { "Retry-After": String(Math.ceil((limit.resetAt - Date.now()) / 1000)) } }
      );
    }

    const body = await request.json();
    const { email } = body;

    if (!email || typeof email !== "string") {
      return NextResponse.json(
        { message: "Email is required" },
        { status: 400 }
      );
    }

    // Check if user exists (but don't reveal this to prevent enumeration)
    const user = await db.user.findUnique({
      where: { email: email.toLowerCase() },
    });

    if (user) {
      // Generate secure token
      const token = crypto.randomBytes(32).toString("hex");
      const expires = new Date(Date.now() + 60 * 60 * 1000); // 1 hour

      // Delete any existing reset tokens for this email
      await db.passwordResetToken.deleteMany({
        where: { email: email.toLowerCase() },
      });

      // Create new reset token
      await db.passwordResetToken.create({
        data: {
          email: email.toLowerCase(),
          token,
          expires,
        },
      });

      // Send password reset email
      const resetUrl = `${process.env.NEXTAUTH_URL}/auth/reset-password?token=${token}&email=${encodeURIComponent(email)}`;

      try {
        await sendPasswordResetEmail({ email, url: resetUrl, expires });
      } catch (emailError) {
        // Don't fail the request if email sending fails
        logger.error({ err: emailError, action: 'send_reset_email' }, 'Failed to send password reset email');
      }
    }

    // Always return success to prevent email enumeration
    return NextResponse.json(
      {
        message: "If an account exists with that email, you will receive a password reset link.",
      },
      { status: 200 }
    );
  } catch (error) {
    logger.error({ err: error, action: 'forgot_password' }, 'Forgot password error');
    return NextResponse.json(
      { message: "An error occurred. Please try again." },
      { status: 500 }
    );
  }
}
