import type { Plan } from '@bmm/llm';
import { Queue } from 'bullmq';
import { getRedis } from './redis.js';

// BullMQ priority: LOWER number = processed sooner. Paid tiers jump ahead of
// free in the shared build queue — this is what makes the "priority build
// queue" plan claim actually true.
const PLAN_PRIORITY: Record<Plan, number> = { enterprise: 1, team: 2, pro: 3, hobby: 4 };
export function buildPriority(plan: Plan): number {
  return PLAN_PRIORITY[plan] ?? 4;
}

export interface BuildJobData {
  buildId: string;
  serverId: string;
  orgId: string;
  prompt: string;
  version: number;
  slug: string;
  serverName: string;
  secrets: Record<string, string>;
  previewId?: string;
}

let queue: Queue<BuildJobData> | null = null;

export function getBuildQueue(): Queue<BuildJobData> {
  if (!queue) {
    queue = new Queue<BuildJobData>('build', {
      connection: getRedis(),
      // Explicit job lifecycle. attempts:1 because a build is non-idempotent
      // (allocates a host port, runs a container, spends an LLM call) — a blind
      // BullMQ retry would double-spend; users re-run via /iterate instead.
      // removeOnComplete/Fail caps Redis growth. (GEN-007)
      defaultJobOptions: { attempts: 1, removeOnComplete: 100, removeOnFail: 500 },
    });
  }
  return queue;
}
