import { describe, expect, it } from "vitest"

import { tryRateLimit } from "../rate-limit"

/**
 * Tests for the rate-limit helper (KAR-517).
 *
 * The helper is a thin wrapper around @upstash/ratelimit. With no
 * UPSTASH_REDIS_REST_URL env var set (the unit-test mode), it behaves
 * as fail-open — every call returns allowed. That's intentional: the
 * helper exists to protect a production deployment, and unit tests must
 * not require an out-of-process Redis instance.
 *
 * End-to-end limit behaviour is owned by Upstash and gets a smoke test
 * in staging.
 */

describe("tryRateLimit (KAR-517)", () => {
  it("returns allowed=true when Upstash env vars are unset (fail-open)", async () => {
    delete process.env.UPSTASH_REDIS_REST_URL
    delete process.env.UPSTASH_REDIS_REST_TOKEN
    const result = await tryRateLimit("test-key", { limit: 5, window: "10 s" })
    expect(result.allowed).toBe(true)
    expect(result.remaining).toBeGreaterThanOrEqual(0)
  })

  it("includes the identifier in the result for log correlation", async () => {
    const result = await tryRateLimit("user:abc", { limit: 10, window: "60 s" })
    expect(result.identifier).toBe("user:abc")
  })
})
