/**
 * Redis Client — Upstash REST only
 *
 * Simplified from dual Upstash/IORedis to Upstash-only (T18).
 * Used exclusively for:
 * - Rate limiting (via @upstash/ratelimit)
 * - Job queue (via lib/queue/job-queue.ts)
 *
 * OTP storage and caching have been migrated to Convex and in-memory cache respectively.
 */

import { Redis } from '@upstash/redis';

/**
 * Whether Upstash Redis is properly configured with REST credentials.
 */
export const redisConfigured = Boolean(
  process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN
);

/**
 * Create Upstash Redis client.
 * Returns a working client when credentials are present,
 * or a dummy client that will fail gracefully when they are not.
 */
function createRedisClient(): Redis {
  const url = process.env.UPSTASH_REDIS_REST_URL;
  const token = process.env.UPSTASH_REDIS_REST_TOKEN;

  if (url && token) {
    return new Redis({ url, token });
  }

  // Build-time / unconfigured fallback — callers should check `redisConfigured` first
  console.warn('[Redis] UPSTASH_REDIS_REST_URL or UPSTASH_REDIS_REST_TOKEN not set — using dummy client');
  return new Redis({
    url: 'https://dummy-redis.upstash.io',
    token: 'dummy-token',
  });
}

export const redis = createRedisClient();

/**
 * Simple health check — returns true if Upstash responds to PING.
 */
export async function checkRedisHealth(): Promise<boolean> {
  if (!redisConfigured) return false;
  try {
    const result = await redis.ping();
    return result === 'PONG';
  } catch (error) {
    console.error('[Redis] Health check failed:', error);
    return false;
  }
}
