import { NextResponse } from "next/server";
import { sql } from "@/db";
import { rateLimit, getClientIp, getRateLimitKey } from "@/lib/rate-limit";
import bcrypt from "bcryptjs";

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

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

  try {
    const body = await request.json();
    const { token, password } = body;

    if (!token || !password) {
      return NextResponse.json({ error: "Token and password required" }, { status: 400 });
    }

    // Clean token prefix
    const cleanToken = token.startsWith("reset_") ? token.slice(6) : token;

    const resets = await sql.unsafe(
      `SELECT * FROM password_resets WHERE token = $1 AND expires_at > NOW() AND used_at IS NULL`,
      [cleanToken]
    );

    if (!resets || resets.length === 0) {
      return NextResponse.json({ error: "Invalid or expired token" }, { status: 400 });
    }

    const reset = resets[0];
    const passwordHash = await bcrypt.hash(password, 12);

    await sql.unsafe(
      `UPDATE users SET password_hash = $1, password_updated_at = NOW() WHERE id = $2`,
      [passwordHash, reset.user_id]
    );

    await sql.unsafe(
      `UPDATE password_resets SET used_at = NOW() WHERE id = $1`,
      [reset.id]
    );

    return NextResponse.json({ success: true, message: "Password updated" });
  } catch (error) {
    console.error("Reset confirm error:", error);
    return NextResponse.json({ error: "Reset failed" }, { status: 500 });
  }
}