import { Redis } from "ioredis";
import { config } from "../config.js";

export type QueueMessage = {
  render_job_uuid: string;
};

export class RenderQueueConsumer {
  private redis: Redis | null = null;

  async connect(): Promise<void> {
    this.redis = new Redis(config.redisUrl, {
      maxRetriesPerRequest: 2,
      lazyConnect: true,
    });

    await this.redis.connect();
  }

  async disconnect(): Promise<void> {
    if (this.redis) {
      await this.redis.quit();
      this.redis = null;
    }
  }

  async popJob(): Promise<QueueMessage | null> {
    if (!this.redis) {
      return null;
    }

    try {
      const result = await this.redis.blpop(
        config.renderQueue,
        config.redisBlockSeconds,
      );

      if (!result) {
        return null;
      }

      const [, payload] = result;
      const parsed = JSON.parse(payload) as Partial<QueueMessage>;

      if (!parsed.render_job_uuid) {
        console.warn("[queue] Ignoring malformed payload:", payload);
        return null;
      }

      return { render_job_uuid: parsed.render_job_uuid };
    } catch (error) {
      console.warn("[queue] Redis unavailable, falling back to API polling:", error);
      return null;
    }
  }
}
