import type { RedisOptions } from 'bullmq';

const redisUrl = process.env.REDIS_URL?.trim() || 'redis://localhost:6379';

const parseRedisConnection = (): RedisOptions => {
  const url = new URL(redisUrl);
  const db = url.pathname && url.pathname !== '/' ? Number(url.pathname.slice(1)) : undefined;

  return {
    host: url.hostname,
    port: url.port ? Number(url.port) : 6379,
    username: url.username ? decodeURIComponent(url.username) : undefined,
    password: url.password ? decodeURIComponent(url.password) : undefined,
    db: Number.isFinite(db) ? db : undefined,
    maxRetriesPerRequest: null,
  };
};

export const redisConnection = parseRedisConnection();
