import assert from "node:assert/strict";
import test from "node:test";
import { SEARCH_QUERY_CACHE_TTL_MS, isFreshSearchCacheHit, normalizeSearchQuery } from "../src/search-cache.js";

test("normalizeSearchQuery trims and lowercases query text", () => {
  assert.equal(normalizeSearchQuery("  Bitcoin PRICE  "), "bitcoin price");
  assert.equal(normalizeSearchQuery("   "), null);
  assert.equal(normalizeSearchQuery(null), null);
});

test("isFreshSearchCacheHit requires fresh persisted payload and no active stream", () => {
  const now = new Date("2026-05-31T12:00:00.000Z");

  assert.equal(
    isFreshSearchCacheHit({ updatedAt: new Date(now.getTime() - SEARCH_QUERY_CACHE_TTL_MS + 1), resultCount: 1 }, now),
    true
  );
  assert.equal(
    isFreshSearchCacheHit({ updatedAt: new Date(now.getTime() - SEARCH_QUERY_CACHE_TTL_MS - 1), resultCount: 1 }, now),
    false
  );
  assert.equal(isFreshSearchCacheHit({ updatedAt: now, resultCount: 0, answerText: "" }, now), false);
  assert.equal(isFreshSearchCacheHit({ updatedAt: now, resultCount: 0, answerText: "answer" }, now), true);
  assert.equal(isFreshSearchCacheHit({ updatedAt: now, resultCount: 1, isActive: true }, now), false);
});
