import { NextResponse } from "next/server";
import { sql } from "@/db";
import { rateLimit, getClientIp, getRateLimitKey } from "@/lib/rate-limit";
import { randomBytes } from "crypto";
import { Resend } from "resend";

const RESEND_API_KEY = process.env.RESEND_API_KEY;
const EMAIL_FROM = process.env.EMAIL_FROM || "Tia <noreply@tia.manohargupta.com>";
const RESET_URL = process.env.NEXT_PUBLIC_APP_URL || "https://tia.manohargupta.com";

export async function POST(request: Request) {
  const ip = getClientIp(request);
  const rateLimitResult = await rateLimit(getRateLimitKey("reset-request", ip), { max: 3, windowSec: 3600 });

  if (!rateLimitResult.success) {
    return NextResponse.json({ error: "Too many requests" }, { status: 429 });
  }

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

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

    const users = await sql.unsafe(`SELECT id FROM users WHERE email = $1`, [email]);

    // Always return success to prevent email enumeration
    if (!users || users.length === 0) {
      return NextResponse.json({ success: true, message: "If email exists, reset link sent" });
    }

    const user = users[0];
    const token = randomBytes(32).toString("hex");
    const expiresAt = new Date();
    expiresAt.setHours(expiresAt.getHours() + 1); // 1 hour

    await sql.unsafe(
      `INSERT INTO password_resets (user_id, token, expires_at) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`,
      [user.id, token, expiresAt.toISOString()]
    );

    const resetLink = `${RESET_URL}/reset-password?token=${token}`;

    // Send email via Resend if API key is configured
    if (RESEND_API_KEY) {
      try {
        const resend = new Resend(RESEND_API_KEY);
        await resend.emails.send({
          from: EMAIL_FROM,
          to: email,
          subject: "Reset your Tia password",
          html: `
            <div style="font-family: system-ui, sans-serif; max-width: 500px; margin: 0 auto;">
              <h2>Reset your Tia password</h2>
              <p>Click the button below to reset your password. This link expires in 1 hour.</p>
              <a href="${resetLink}" style="display: inline-block; background: #2563eb; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; margin: 16px 0;">Reset Password</a>
              <p style="color: #6b7280; font-size: 14px;">If you didn't request this, you can safely ignore this email.</p>
            </div>
          `,
        });
        console.log(`[RESET-EMAIL-SENT] user=${user.id} email=${email}`);
      } catch (emailError) {
        console.error("[RESET-EMAIL-FAILED]", emailError);
      }
    } else {
      // Development fallback
      console.log(`[RESET-TOKEN] user=${user.id} email=${email} token=reset_${token} expires=${expiresAt.toISOString()}`);
    }

    return NextResponse.json({ success: true, message: "If email exists, reset link sent" });
  } catch (error) {
    console.error("Reset request error:", error);
    return NextResponse.json({ success: true, message: "If email exists, reset link sent" });
  }
}