// src/index.ts
import { createClient, RedisClientType, RedisClientPoolType } from 'redis';
import { randomBytes } from 'crypto';

export interface JobPayload {
  class: string;
  queue: string;
  args: unknown[];
  jid: string;
  created_at: number;
  enqueued_at?: number;
  [key: string]: unknown;
}

export class SidekiqClient {
  private redis: RedisClientType | RedisClientPoolType;

  /**
   * Initialize SidekiqClient.
   *
   * @param redisUrlOrClient - Redis connection URL (string) or a RedisClientType/RedisClientPoolType instance.
   */
  constructor(redisUrlOrClient: string | RedisClientType | RedisClientPoolType) {
    if (typeof redisUrlOrClient === 'string') {
      // create a new client from URL
      this.redis = createClient({ url: redisUrlOrClient });
      // auto-connect
      this.redis.connect().catch((err) => {
        throw new Error(`Failed to connect to Redis: ${err}`);
      });
    } else {
      this.redis = redisUrlOrClient;
    }
  }

  /**
   * Enqueue a job for immediate asynchronous processing.
   *
   * @param queue - Name of the queue.
   * @param jobClass - Name of the job class.
   * @param args - Array of job arguments.
   * @param options - Additional options (e.g., retry settings, metadata).
   * @returns The JID (24-character hex string).
   */
  async performAsync(
    queue: string,
    jobClass: string,
    args: unknown[],
    options: Record<string, unknown> = {}
  ): Promise<string> {
    const job = this.buildJobPayload(queue, jobClass, args, options, true);
    // lpush "queue:<queue>" "<JSON>"
    await this.redis.lPush(`queue:${queue}`, JSON.stringify(job));
    return job.jid;
  }

  /**
   * Schedule a job to run after a delay (in miliseconds).
   *
   * @param msFromNow - Delay (in miliseconds) before job should run.
   * @param queue - Name of the queue.
   * @param jobClass - Name of the job class.
   * @param args - Array of job arguments.
   * @param options - Additional options.
   * @returns The JID (24-character hex string).
   */
  async performIn(
    msFromNow: number,
    queue: string,
    jobClass: string,
    args: unknown[],
    options: Record<string, unknown> = {}
  ): Promise<string> {
    const timestamp = Date.now() + msFromNow;
    return this.zaddScheduled(queue, jobClass, args, timestamp, options);
  }

  /**
   * Schedule a job to run at a specific Unix timestamp.
   *
   * @param unixTimestamp - When the job should run (miliseconds since epoch).
   * @param queue - Name of the queue.
   * @param jobClass - Name of the job class.
   * @param args - Array of job arguments.
   * @param options - Additional options.
   * @returns The JID (24-character hex string).
   */
  async performAt(
    unixTimestamp: number,
    queue: string,
    jobClass: string,
    args: unknown[],
    options: Record<string, unknown> = {}
  ): Promise<string> {
    // Ensure the timestamp is in seconds, sidekiq uses seconds.fraction
    // but node and most peaople programin in node use milliseconds
    const timestampInSeconds = unixTimestamp / 1000;

    return this.zaddScheduled(queue, jobClass, args, timestampInSeconds, options);
  }

  /**
   * Internal: add a scheduled job to the "schedule" sorted set.
   */
  private async zaddScheduled(
    queue: string,
    jobClass: string,
    args: unknown[],
    timestamp: number,
    options: Record<string, unknown>
  ): Promise<string> {
    const job = this.buildJobPayload(queue, jobClass, args, options, false);
    // zAdd "schedule" { score: timestamp, value: JSON.stringify(job) }
    // In Redis v4, zAdd takes an array of { score, value } or a single object
    await this.redis.zAdd('schedule', {
      score: timestamp,
      value: JSON.stringify(job)
    });
    return job.jid;
  }

  /**
   * Build the job payload (same fields as Python version).
   */
  private buildJobPayload(
    queue: string,
    jobClass: string,
    args: unknown[],
    options: Record<string, unknown>,
    includeEnqueued: boolean
  ): JobPayload {
    const now = Date.now() / 1000; // seconds.fraction
    const jid = randomBytes(12).toString('hex'); // 24 hex chars

    const base: JobPayload = {
      class: jobClass,
      queue,
      args,
      jid,
      created_at: now
    };

    if (includeEnqueued) {
      base.enqueued_at = now;
    }

    // Merge any extra options on top of base
    return { ...base, ...options };
  }
}
