import { NextResponse } from "next/server"

import { auth } from "@/auth"
import { rateLimit, rateLimitKey, rateLimitHeaders, RATE_LIMIT_RULES } from "@/shared/lib/rate-limit"

export const dynamic = "force-dynamic"

/**
 * Test endpoint for the rate limiter (memory or redis based on RATE_LIMIT_DRIVER).
 * Applies a strict 5-requests-per-minute limit per user so you can
 * observe 429 responses quickly during manual testing.
 *
 * Usage:
 *   curl -X GET http://localhost:3000/api/rate-limit-test \
 *     -H "Cookie: next-auth.session-token=<token>"
 */
export async function GET() {
  const session = await auth()
  const userId = String(session?.user?.id ?? "").trim()
  if (!userId) {
    return NextResponse.json({ success: false, message: "Unauthorized" }, { status: 401 })
  }

  const limitKey = rateLimitKey("test", userId)
  const limit = await rateLimit({ key: limitKey, ...RATE_LIMIT_RULES.PASSWORD_CHANGE })

  if (!limit.success) {
    return NextResponse.json(
      {
        success: false,
        message: "Rate limit exceeded",
        remaining: limit.remaining,
        retryAfterMs: limit.retryAfterMs,
      },
      { status: 429, headers: rateLimitHeaders(limit) }
    )
  }

  return NextResponse.json(
    {
      success: true,
      message: "Request allowed",
      remaining: limit.remaining,
      resetTime: new Date(limit.resetTime).toISOString(),
    },
    { headers: rateLimitHeaders(limit) }
  )
}
