import type { Job } from 'bullmq';
import { logger } from '../logger.js';

/**
 * Removes a BullMQ job when present. Locked (active) jobs cannot be removed —
 * those errors are swallowed so callers can still schedule a replacement jobId
 * or rely on removeOnComplete after the worker finishes.
 * Jobs that belong to a Job Scheduler must be removed via removeJobScheduler;
 * direct remove is ignored here.
 */
export async function safeRemoveBullJob(
  job: Job | null | undefined,
  context?: { label?: string; jobId?: string }
): Promise<void> {
  if (!job) {
    return;
  }
  try {
    await job.remove();
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    if (
      message.includes('locked') ||
      message.includes('could not be removed') ||
      message.includes('belongs to a job scheduler')
    ) {
      logger.warn(
        { error, jobId: context?.jobId ?? job.id, label: context?.label },
        'BullMQ job could not be removed directly; skipping'
      );
      return;
    }
    throw error;
  }
}
