import { beforeEach, describe, expect, test, vi } from "vitest";
import { logger } from "@formbricks/logger";
import { CacheService } from "./service";
import type { RedisClient } from "./types/client";
import { ErrorCode } from "./types/error";
import type { CacheKey } from "./types/keys";

// Mock logger
vi.mock("@formbricks/logger", () => ({
  logger: {
    error: vi.fn(),
    warn: vi.fn(),
    info: vi.fn(),
    debug: vi.fn(),
  },
}));

interface MockRedisClient {
  get: ReturnType<typeof vi.fn>;
  setEx: ReturnType<typeof vi.fn>;
  del: ReturnType<typeof vi.fn>;
  exists: ReturnType<typeof vi.fn>;
  ping: ReturnType<typeof vi.fn>;
  isReady: boolean;
  isOpen: boolean;
}

describe("CacheService", () => {
  let mockRedis: MockRedisClient;
  let cacheService: CacheService;

  beforeEach(() => {
    mockRedis = {
      get: vi.fn(),
      setEx: vi.fn(),
      del: vi.fn(),
      exists: vi.fn(),
      ping: vi.fn().mockResolvedValue("PONG"),
      isReady: true,
      isOpen: true,
    };
    cacheService = new CacheService(mockRedis as unknown as RedisClient);
  });

  test("bounds a raw Redis operation before discarding a stalled client", async () => {
    vi.useFakeTimers();
    try {
      const onTimeout = vi.fn();
      cacheService = new CacheService(mockRedis as unknown as RedisClient, onTimeout);
      mockRedis.get.mockReturnValue(new Promise<string>(() => {}));

      const operation = cacheService.runRedisOperation((redis) => redis.get("test:key"));
      // eslint-disable-next-line vitest/valid-expect -- awaited below, once the fake timers have fired the rejection
      const assertion = expect(operation).rejects.toThrow("Redis operation timed out");
      await vi.advanceTimersByTimeAsync(500);
      await assertion;

      expect(onTimeout).not.toHaveBeenCalled();
      await vi.advanceTimersByTimeAsync(1000);
      expect(onTimeout).toHaveBeenCalledOnce();
      expect(vi.getTimerCount()).toBe(0);
    } finally {
      vi.useRealTimers();
    }
  });

  describe("get", () => {
    test("should return parsed JSON value when found", async () => {
      const key = "test:key" as CacheKey;
      const value = { data: "test" };
      mockRedis.get.mockResolvedValue(JSON.stringify(value));

      const result = await cacheService.get(key);

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.data).toEqual(value);
      }
      expect(mockRedis.get).toHaveBeenCalledWith(key);
    });

    test("should return null when key not found", async () => {
      const key = "test:key" as CacheKey;
      mockRedis.get.mockResolvedValue(null);

      const result = await cacheService.get(key);

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.data).toBeNull();
      }
    });

    test("should return error when JSON parse fails (corrupted data)", async () => {
      const key = "test:key" as CacheKey;
      const corruptedValue = "invalid json {broken";
      mockRedis.get.mockResolvedValue(corruptedValue);

      const result = await cacheService.get(key);

      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error.code).toBe(ErrorCode.CacheCorruptionError);
      }
      expect(logger.warn).toHaveBeenCalledWith(
        expect.objectContaining({
          key,
          parseError: expect.objectContaining({
            name: "SyntaxError",
            message: expect.stringContaining("JSON") as string,
          }) as Error,
        }),
        "Corrupted cache data detected, treating as cache miss"
      );
    });

    test("should return validation error for empty key", async () => {
      const key = "" as CacheKey;

      const result = await cacheService.get(key);

      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error.code).toBe(ErrorCode.CacheValidationError);
      }
    });

    test("should return validation error for whitespace-only key", async () => {
      const key = "   " as CacheKey;

      const result = await cacheService.get(key);

      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error.code).toBe(ErrorCode.CacheValidationError);
      }
    });

    test("should return error when Redis operation fails", async () => {
      const key = "test:key" as CacheKey;
      mockRedis.get.mockRejectedValue(new Error("Redis connection failed"));

      const result = await cacheService.get(key);

      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error.code).toBe(ErrorCode.RedisOperationError);
      }
      expect(logger.error).toHaveBeenCalledWith(
        { error: expect.any(Error), key }, // eslint-disable-line @typescript-eslint/no-unsafe-assignment -- Testing error handling with any Error type
        "Cache get operation failed"
      );
    });

    test("should handle string values correctly", async () => {
      const key = "test:key" as CacheKey;
      const value = "simple string";
      mockRedis.get.mockResolvedValue(JSON.stringify(value));

      const result = await cacheService.get(key);

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.data).toBe(value);
      }
    });

    test("should handle number values correctly", async () => {
      const key = "test:key" as CacheKey;
      const value = 42;
      mockRedis.get.mockResolvedValue(JSON.stringify(value));

      const result = await cacheService.get(key);

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.data).toBe(value);
      }
    });

    test("should handle boolean values correctly", async () => {
      const key = "test:key" as CacheKey;
      const value = false;
      mockRedis.get.mockResolvedValue(JSON.stringify(value));

      const result = await cacheService.get(key);

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.data).toBe(value);
      }
    });

    test("should handle nested object values correctly", async () => {
      const key = "test:key" as CacheKey;
      const value = { nested: { deeply: { value: "test" } }, array: [1, 2, 3] };
      mockRedis.get.mockResolvedValue(JSON.stringify(value));

      const result = await cacheService.get(key);

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.data).toEqual(value);
      }
    });
  });

  describe("exists", () => {
    test("should return true when key exists", async () => {
      const key = "test:key" as CacheKey;
      mockRedis.exists.mockResolvedValue(1);

      const result = await cacheService.exists(key);

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.data).toBe(true);
      }
      expect(mockRedis.exists).toHaveBeenCalledWith(key);
    });

    test("should return false when key does not exist", async () => {
      const key = "test:key" as CacheKey;
      mockRedis.exists.mockResolvedValue(0);

      const result = await cacheService.exists(key);

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.data).toBe(false);
      }
    });

    test("should return validation error for empty key", async () => {
      const key = "" as CacheKey;

      const result = await cacheService.exists(key);

      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error.code).toBe(ErrorCode.CacheValidationError);
      }
    });

    test("should return error when Redis operation fails", async () => {
      const key = "test:key" as CacheKey;
      mockRedis.exists.mockRejectedValue(new Error("Redis connection failed"));

      const result = await cacheService.exists(key);

      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error.code).toBe(ErrorCode.RedisOperationError);
      }
      expect(logger.error).toHaveBeenCalledWith(
        { error: expect.any(Error), key }, // eslint-disable-line @typescript-eslint/no-unsafe-assignment -- Testing error handling with any Error type
        "Cache exists operation failed"
      );
    });

    test("should handle multiple keys existing", async () => {
      const key = "test:key" as CacheKey;
      mockRedis.exists.mockResolvedValue(2); // Multiple keys exist

      const result = await cacheService.exists(key);

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.data).toBe(true);
      }
    });
  });

  describe("set", () => {
    test("should store JSON serialized value with TTL", async () => {
      const key = "test:key" as CacheKey;
      const value = { data: "test" };
      const ttlMs = 60000;

      const result = await cacheService.set(key, value, ttlMs);

      expect(result.ok).toBe(true);
      expect(mockRedis.setEx).toHaveBeenCalledWith(key, 60, JSON.stringify(value));
    });

    test("should convert TTL from milliseconds to seconds", async () => {
      const key = "test:key" as CacheKey;
      const value = "test";
      const ttlMs = 5500; // 5.5 seconds

      const result = await cacheService.set(key, value, ttlMs);

      expect(result.ok).toBe(true);
      expect(mockRedis.setEx).toHaveBeenCalledWith(key, 5, JSON.stringify(value));
    });

    test("should warn and skip the write when value is undefined", async () => {
      const key = "test:key" as CacheKey;
      const value = undefined;
      const ttlMs = 60000;

      const result = await cacheService.set(key, value, ttlMs);

      expect(result.ok).toBe(true);
      expect(mockRedis.setEx).not.toHaveBeenCalled();
      expect(logger.warn).toHaveBeenCalledWith(
        { key, ttlMs },
        "cache.set called with undefined; skipping write"
      );
    });

    test("should store null values as JSON", async () => {
      const key = "test:key" as CacheKey;
      const value = null;
      const ttlMs = 60000;

      const result = await cacheService.set(key, value, ttlMs);

      expect(result.ok).toBe(true);
      expect(mockRedis.setEx).toHaveBeenCalledWith(key, 60, "null");
    });

    test("should return validation error for invalid TTL", async () => {
      const key = "test:key" as CacheKey;
      const value = "test";

      const result1 = await cacheService.set(key, value, 0);
      const result2 = await cacheService.set(key, value, -1);
      const result3 = await cacheService.set(key, value, 500); // Below 1000ms minimum

      expect(result1.ok).toBe(false);
      expect(result2.ok).toBe(false);
      expect(result3.ok).toBe(false);
      if (!result1.ok) {
        expect(result1.error.code).toBe(ErrorCode.CacheValidationError);
      }
    });

    test("should return validation error for empty key", async () => {
      const key = "" as CacheKey;
      const value = "test";

      const result = await cacheService.set(key, value, 1000);

      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error.code).toBe(ErrorCode.CacheValidationError);
      }
    });

    test("should return error when Redis operation fails", async () => {
      const key = "test:key" as CacheKey;
      const value = "test";
      const ttlMs = 60000;
      mockRedis.setEx.mockRejectedValue(new Error("Redis connection failed"));

      const result = await cacheService.set(key, value, ttlMs);

      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error.code).toBe(ErrorCode.RedisOperationError);
      }
      expect(logger.error).toHaveBeenCalledWith(
        { error: expect.any(Error), key, ttlMs }, // eslint-disable-line @typescript-eslint/no-unsafe-assignment -- Testing error handling with any Error type
        "Cache set operation failed"
      );
    });

    test("should handle complex data types correctly", async () => {
      const key = "test:key" as CacheKey;
      const value = {
        string: "test",
        number: 42,
        boolean: true,
        array: [1, 2, 3],
        nested: { level: { deep: "value" } },
        nullValue: null,
      };
      const ttlMs = 60000;

      const result = await cacheService.set(key, value, ttlMs);

      expect(result.ok).toBe(true);
      expect(mockRedis.setEx).toHaveBeenCalledWith(key, 60, JSON.stringify(value));
    });
  });

  describe("del", () => {
    test("should delete single key", async () => {
      const key = "test:key" as CacheKey;

      const result = await cacheService.del([key]);

      expect(result.ok).toBe(true);
      expect(mockRedis.del).toHaveBeenCalledWith([key]);
    });

    test("should delete multiple keys", async () => {
      const keys = ["test:key1", "test:key2"] as CacheKey[];

      const result = await cacheService.del(keys);

      expect(result.ok).toBe(true);
      expect(mockRedis.del).toHaveBeenCalledWith(keys);
    });

    test("should be idempotent (not throw if key missing)", async () => {
      const key = "nonexistent:key" as CacheKey;
      mockRedis.del.mockResolvedValue(0);

      const result = await cacheService.del([key]);

      expect(result.ok).toBe(true);
    });

    test("should handle empty array gracefully", async () => {
      const result = await cacheService.del([]);

      expect(result.ok).toBe(true);
      expect(mockRedis.del).not.toHaveBeenCalled();
    });

    test("should return validation error for empty key in array", async () => {
      const keys = ["valid:key", ""] as CacheKey[];

      const result = await cacheService.del(keys);

      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error.code).toBe(ErrorCode.CacheValidationError);
      }
    });

    test("should return error when Redis is not ready/open", async () => {
      const keys = ["test:key1", "test:key2"] as CacheKey[];
      mockRedis.isReady = false;
      mockRedis.isOpen = false;

      const result = await cacheService.del(keys);

      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error.code).toBe(ErrorCode.RedisConnectionError);
      }
    });

    test("should return error when Redis operation fails", async () => {
      const keys = ["test:key1", "test:key2"] as CacheKey[];
      mockRedis.del.mockRejectedValue(new Error("Redis connection failed"));

      const result = await cacheService.del(keys);

      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error.code).toBe(ErrorCode.RedisOperationError);
      }
      expect(logger.error).toHaveBeenCalledWith(
        { error: expect.any(Error), keys }, // eslint-disable-line @typescript-eslint/no-unsafe-assignment -- Testing error handling with any Error type
        "Cache delete operation failed"
      );
    });

    test("should validate all keys before deletion", async () => {
      const keys = ["valid:key1", "   ", "valid:key2"] as CacheKey[];

      const result = await cacheService.del(keys);

      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error.code).toBe(ErrorCode.CacheValidationError);
      }
      expect(mockRedis.del).not.toHaveBeenCalled();
    });
  });

  describe("getRedisClient", () => {
    test("should return the Redis client instance when ready", () => {
      const result = cacheService.getRedisClient();

      expect(result).toBe(mockRedis);
    });

    test("should return null when Redis is not ready", () => {
      mockRedis.isReady = false;

      const result = cacheService.getRedisClient();

      expect(result).toBeNull();
    });

    test("should return null when Redis is not open", () => {
      mockRedis.isOpen = false;

      const result = cacheService.getRedisClient();

      expect(result).toBeNull();
    });
  });

  describe("isRedisAvailable", () => {
    test("should return true when Redis is ready, open, and ping succeeds", async () => {
      mockRedis.ping.mockResolvedValue("PONG");

      const result = await cacheService.isRedisAvailable();

      expect(result).toBe(true);
      expect(mockRedis.ping).toHaveBeenCalledOnce();
    });

    test("should return false when Redis is not ready", async () => {
      mockRedis.isReady = false;
      mockRedis.ping.mockResolvedValue("PONG");

      const result = await cacheService.isRedisAvailable();

      expect(result).toBe(false);
      expect(mockRedis.ping).not.toHaveBeenCalled();
    });

    test("should return false when Redis is not open", async () => {
      mockRedis.isOpen = false;
      mockRedis.ping.mockResolvedValue("PONG");

      const result = await cacheService.isRedisAvailable();

      expect(result).toBe(false);
      expect(mockRedis.ping).not.toHaveBeenCalled();
    });

    test("should return false when Redis ping fails", async () => {
      mockRedis.ping.mockRejectedValue(new Error("Connection lost"));

      const result = await cacheService.isRedisAvailable();

      expect(result).toBe(false);
      expect(mockRedis.ping).toHaveBeenCalledOnce();
      expect(logger.debug).toHaveBeenCalledWith(
        { error: expect.any(Error) }, // eslint-disable-line @typescript-eslint/no-unsafe-assignment -- Testing error handling with any Error type
        "Redis ping failed during availability check"
      );
    });

    test("should return false when ping times out", async () => {
      // Mock ping to hang indefinitely
      const hangingPromise = new Promise(() => {
        // This promise never resolves to simulate timeout
      });
      mockRedis.ping.mockReturnValue(hangingPromise);

      const result = await cacheService.isRedisAvailable();

      expect(result).toBe(false);
      expect(mockRedis.ping).toHaveBeenCalledOnce();
    });

    test("should handle different ping responses correctly", async () => {
      // Test with standard PONG response
      mockRedis.ping.mockResolvedValue("PONG");
      let result = await cacheService.isRedisAvailable();
      expect(result).toBe(true);

      // Test with custom ping message
      mockRedis.ping.mockResolvedValue("custom-message");
      result = await cacheService.isRedisAvailable();
      expect(result).toBe(true);

      // Test with empty response (still success if no error thrown)
      mockRedis.ping.mockResolvedValue("");
      result = await cacheService.isRedisAvailable();
      expect(result).toBe(true);
    });

    test("should be async and return Promise<boolean>", async () => {
      mockRedis.ping.mockResolvedValue("PONG");

      const result = cacheService.isRedisAvailable();

      expect(result).toBeInstanceOf(Promise);
      expect(await result).toBe(true);
    });
  });

  describe("withCache", () => {
    test("should return cached value when available", async () => {
      const key = "test:key" as CacheKey;
      const cachedValue = { data: "cached" };
      const fn = vi.fn().mockResolvedValue({ data: "fresh" });

      mockRedis.get.mockResolvedValue(JSON.stringify(cachedValue));

      const result = await cacheService.withCache(fn, key, 60000);

      expect(result).toEqual(cachedValue);
      expect(fn).not.toHaveBeenCalled();
    });

    test("should compute and cache value when cache miss", async () => {
      const key = "test:key" as CacheKey;
      const freshValue = { data: "fresh" };
      const fn = vi.fn().mockResolvedValue(freshValue);

      mockRedis.get.mockResolvedValue(null);
      mockRedis.exists.mockResolvedValue(0); // Key doesn't exist

      const result = await cacheService.withCache(fn, key, 60000);

      expect(result).toEqual(freshValue);
      expect(fn).toHaveBeenCalledOnce();
      expect(mockRedis.setEx).toHaveBeenCalledWith(key, 60, JSON.stringify(freshValue));
    });

    test("should return fresh value when cache operation fails", async () => {
      const key = "test:key" as CacheKey;
      const freshValue = { data: "fresh" };
      const fn = vi.fn().mockResolvedValue(freshValue);

      mockRedis.get.mockRejectedValue(new Error("Redis connection failed"));

      const result = await cacheService.withCache(fn, key, 60000);

      expect(result).toEqual(freshValue);
      expect(fn).toHaveBeenCalledOnce();
    });

    test("should treat stringified null as a cache miss and re-execute fn", async () => {
      const key = "test:key" as CacheKey;
      const freshValue = { data: "fresh" };
      const fn = vi.fn().mockResolvedValue(freshValue);

      // Bare JSON null is a miss for non-null cache-aside calls.
      mockRedis.get.mockResolvedValue("null");

      const result = await cacheService.withCache(fn, key, 60000);

      expect(result).toEqual(freshValue);
      expect(fn).toHaveBeenCalledOnce();
      expect(mockRedis.setEx).toHaveBeenCalledWith(key, 60, JSON.stringify(freshValue));
    });

    test("should not surface stale null under the original GET/EXISTS race window", async () => {
      // Simulates the removed GET/EXISTS race from ENG-1047.
      const key = "test:key" as CacheKey;
      const freshValue = { data: "fresh-from-fn" };
      const fn = vi.fn().mockResolvedValue(freshValue);

      mockRedis.get.mockResolvedValue(null);
      mockRedis.exists.mockResolvedValue(1);

      const result = await cacheService.withCache(fn, key, 60000);

      expect(result).toEqual(freshValue);
      expect(fn).toHaveBeenCalledOnce();
      expect(mockRedis.exists).not.toHaveBeenCalled();
    });

    test("should not persist null returned via type erasure (no recompute stampede)", async () => {
      // withCache<T> is constrained to NonNullable<unknown>, but a caller can
      // still bypass that through unknown/any plumbing or an erased generic.
      // If null were written, the read path would treat it as a perpetual miss,
      // re-running fn() and rewriting "null" on every request for a hot key.
      const key = "test:key" as CacheKey;
      const fn = vi.fn().mockResolvedValue(null);

      mockRedis.get.mockResolvedValue(null); // cache miss

      const result = await cacheService.withCache(fn, key, 60000);

      expect(result).toBeNull();
      expect(fn).toHaveBeenCalledOnce();
      expect(mockRedis.setEx).not.toHaveBeenCalled();
    });
  });

  describe("withCacheNullable", () => {
    // Keep the nullable wire format explicit in assertions.
    const box = (value: unknown): string => JSON.stringify({ __fb_nullable_v1: true, value });

    test("should return cached null without executing fn when boxed null is stored", async () => {
      const key = "test:nullable-key" as CacheKey;
      const fn = vi.fn().mockResolvedValue({ id: "fresh" });

      mockRedis.get.mockResolvedValue(box(null));

      const result = await cacheService.withCacheNullable(fn, key, 60000);

      expect(result).toBeNull();
      expect(fn).not.toHaveBeenCalled();
    });

    test("should compute, box, and cache null on miss", async () => {
      const key = "test:nullable-key" as CacheKey;
      const fn = vi.fn().mockResolvedValue(null);

      mockRedis.get.mockResolvedValue(null);

      const result = await cacheService.withCacheNullable(fn, key, 60000);

      expect(result).toBeNull();
      expect(fn).toHaveBeenCalledOnce();
      expect(mockRedis.setEx).toHaveBeenCalledWith(key, 60, box(null));
    });

    test("should compute, box, and cache a real value on miss", async () => {
      const key = "test:nullable-key" as CacheKey;
      const freshValue = { id: "real" };
      const fn = vi.fn().mockResolvedValue(freshValue);

      mockRedis.get.mockResolvedValue(null);

      const result = await cacheService.withCacheNullable(fn, key, 60000);

      expect(result).toEqual(freshValue);
      expect(fn).toHaveBeenCalledOnce();
      expect(mockRedis.setEx).toHaveBeenCalledWith(key, 60, box(freshValue));
    });

    test("should return boxed cached value without executing fn", async () => {
      const key = "test:nullable-key" as CacheKey;
      const cachedValue = { id: "cached" };
      const fn = vi.fn().mockResolvedValue({ id: "fresh" });

      mockRedis.get.mockResolvedValue(box(cachedValue));

      const result = await cacheService.withCacheNullable(fn, key, 60000);

      expect(result).toEqual(cachedValue);
      expect(fn).not.toHaveBeenCalled();
    });

    test("should treat unboxed legacy values as a cache miss and overwrite with boxed value", async () => {
      const key = "test:nullable-key" as CacheKey;
      const legacyCachedValue = { id: "legacy" };
      const freshValue = { id: "fresh" };
      const fn = vi.fn().mockResolvedValue(freshValue);

      mockRedis.get.mockResolvedValue(JSON.stringify(legacyCachedValue));

      const result = await cacheService.withCacheNullable(fn, key, 60000);

      expect(result).toEqual(freshValue);
      expect(fn).toHaveBeenCalledOnce();
      expect(mockRedis.setEx).toHaveBeenCalledWith(key, 60, box(freshValue));
      expect(logger.debug).toHaveBeenCalledWith(
        { key, ttlMs: 60000 },
        "Nullable cache entry is missing marker or value field; treating as cache miss and refreshing"
      );
    });

    test("should treat a marker-less object with a `value` field as a cache miss", async () => {
      const key = "test:nullable-key" as CacheKey;
      const collidingShape = { value: { id: "colliding" }, otherField: 123 };
      const freshValue = { id: "fresh" };
      const fn = vi.fn().mockResolvedValue(freshValue);

      mockRedis.get.mockResolvedValue(JSON.stringify(collidingShape));

      const result = await cacheService.withCacheNullable(fn, key, 60000);

      expect(result).toEqual(freshValue);
      expect(fn).toHaveBeenCalledOnce();
      expect(mockRedis.setEx).toHaveBeenCalledWith(key, 60, box(freshValue));
    });

    test("should treat a marker-only nullable envelope as a cache miss", async () => {
      const key = "test:nullable-key" as CacheKey;
      const malformedBox = { __fb_nullable_v1: true };
      const freshValue = { id: "fresh" };
      const fn = vi.fn().mockResolvedValue(freshValue);

      mockRedis.get.mockResolvedValue(JSON.stringify(malformedBox));

      const result = await cacheService.withCacheNullable(fn, key, 60000);

      expect(result).toEqual(freshValue);
      expect(fn).toHaveBeenCalledOnce();
      expect(mockRedis.setEx).toHaveBeenCalledWith(key, 60, box(freshValue));
    });

    test("should not cache undefined returned by a nullable callback", async () => {
      const key = "test:nullable-key" as CacheKey;
      const fn = vi.fn().mockResolvedValue(undefined);

      mockRedis.get.mockResolvedValue(null);

      const result = await cacheService.withCacheNullable(fn, key, 60000);

      expect(result).toBeUndefined();
      expect(fn).toHaveBeenCalledOnce();
      expect(mockRedis.setEx).not.toHaveBeenCalled();
    });

    test("should execute function directly when cache fails", async () => {
      const key = "test:key" as CacheKey;
      const expectedResult = { data: "result" };
      const fn = vi.fn().mockResolvedValue(expectedResult);

      mockRedis.get.mockRejectedValue(new Error("Redis connection failed"));

      const result = await cacheService.withCache(fn, key, 60000);

      // withCache now always returns the function result, even when cache fails
      expect(result).toEqual(expectedResult);
      expect(fn).toHaveBeenCalledOnce();
    });

    test("should execute function directly when validation fails", async () => {
      const invalidKey = "" as CacheKey; // Empty key should fail validation
      const expectedResult = { data: "result" };
      const fn = vi.fn().mockResolvedValue(expectedResult);

      const result = await cacheService.withCache(fn, invalidKey, 60000);

      expect(result).toEqual(expectedResult);
      expect(fn).toHaveBeenCalledOnce();
      // Should not attempt any cache operations when validation fails
      expect(mockRedis.get).not.toHaveBeenCalled();
      expect(mockRedis.setEx).not.toHaveBeenCalled();
    });

    test("should execute function directly when TTL validation fails", async () => {
      const key = "test:key" as CacheKey;
      const invalidTtl = 500; // Below minimum TTL of 1000ms
      const expectedResult = { data: "result" };
      const fn = vi.fn().mockResolvedValue(expectedResult);

      const result = await cacheService.withCache(fn, key, invalidTtl);

      expect(result).toEqual(expectedResult);
      expect(fn).toHaveBeenCalledOnce();
      // Should not attempt any cache operations when validation fails
      expect(mockRedis.get).not.toHaveBeenCalled();
      expect(mockRedis.setEx).not.toHaveBeenCalled();
    });
  });
});
