/**
 * Cloudflare Queue consumer for the `multideal-llm-jobs-preview` queue.
 *
 * Phase 1: coarse batch handler — delegates the full runProcessLlmJobs sweep
 * once per batch delivery. Phase 2 will make this per-message.
 *
 * NOTE (Phase 1): see outbox-consumer.ts for the same caveat about the
 * Astro adapter not forwarding the `queue` export. Use
 * `POST /api/queues/llm-jobs` for manual testing.
 *
 * Messages: { jobId: string }
 */

import { runProcessLlmJobs } from '../cron/process-llm-jobs.js';
import type { LlmCronEnv } from '../cron/process-llm-jobs.js';
import { withSentry } from '@/server/observability/with-sentry';
import { captureCaught } from '@/server/observability/capture.server';

export const handleLlmJobsBatch = withSentry(
  async (batch: MessageBatch<{ jobId: string }>, env: LlmCronEnv): Promise<void> => {
    // Phase 1: one sweep per batch, regardless of individual message count.
    try {
      await runProcessLlmJobs(env);
      batch.ackAll();
    } catch (err) {
      console.error(
        JSON.stringify({
          event: 'llm_jobs_batch_failed',
          batchSize: batch.messages.length,
          error: err instanceof Error ? err.message : String(err),
        }),
      );
      captureCaught(err, {
        scope: 'queue.llm-jobs-consumer',
        severity: 'error',
        extra: { batchSize: batch.messages.length },
      });
      batch.retryAll();
    }
  },
  { name: 'queue.llm-jobs', kind: 'queue' },
);
