/**
 * LLM Jobs queue producer helper.
 *
 * Wraps `env.LLM_JOBS_QUEUE.send({ jobId })` with structured logging.
 * Call this immediately after any `enqueueLlmJob(db, ...)` or
 * `enqueueVendorAdmissionReviewOnce(db, ...)` succeeds, OUTSIDE any
 * database transaction.
 *
 * Fire-and-forget semantics: if the queue send fails, the 30-min cron backstop
 * drains the PENDING job within 30 minutes.
 * We still await here so the error is surfaced in request logs.
 */

import { captureCaught } from '@/server/observability/capture.server';

export interface LlmJobsQueueEnv {
  LLM_JOBS_QUEUE: Queue<{ jobId: string }>;
}

export interface JobRunnerNudgeCtx {
  waitUntil?: (p: Promise<unknown>) => void;
}

/**
 * Send a job ID to the LLM_JOBS_QUEUE so the worker queue consumer processes
 * it immediately rather than waiting for the next cron run.
 *
 * @param env   - Any env object with LLM_JOBS_QUEUE binding.
 * @param jobId - The llm_jobs.id returned by enqueueLlmJob / enqueueVendorAdmissionReviewOnce.
 */
export async function sendLlmJobToQueue(
  env: LlmJobsQueueEnv,
  jobId: string,
  ctx?: JobRunnerNudgeCtx,
): Promise<void> {
  const sendPromise = env.LLM_JOBS_QUEUE.send({ jobId });
  if (ctx?.waitUntil) {
    ctx.waitUntil(sendPromise);
  }
  try {
    await sendPromise;
  } catch (err) {
    // Non-fatal: 30-min cron backstop will pick it up.
    console.error(
      JSON.stringify({
        event: 'llm_job_queue_send_failed',
        jobId,
        error: err instanceof Error ? err.message : String(err),
      }),
    );
    captureCaught(err, {
      scope: 'queue.llm-jobs-producer',
      severity: 'warning',
      extra: { jobId },
    });
  }
}
