/**
 * Outbox queue producer helper.
 *
 * After a tx-bound outbox row is inserted and the transaction commits,
 * call `enqueueOutbox(outboxId)` to push the row id onto the
 * `multideal-outbox-preview` queue so the DO worker consumer can dispatch
 * the side effect promptly.
 *
 * Design decisions:
 * - Does NOT throw on queue-send failure.  The `process-outbox` cron is the
 *   safety backstop — it will pick up any row the queue path missed.  Throwing
 *   here would roll back the calling transaction, which is far worse than a
 *   slightly-delayed email.
 * - Imports `env` directly (per §4: never thread env through a dozen args).
 * - Logs structured JSON on failure for Sentry / Cloudflare Logs ingestion.
 */

import { env } from '@/server/env.js';

/**
 * Enqueue an outbox row id onto the Cloudflare Queue after the DB tx commits.
 *
 * Must be called OUTSIDE the Drizzle transaction (after tx resolves) so the
 * queue message is only sent for rows that are actually committed.
 *
 * @param outboxId — the `outbox.id` UUID returned from the INSERT.
 */
export async function enqueueOutbox(outboxId: string): Promise<void> {
  try {
    await env.OUTBOX_QUEUE.send({ outboxId });
  } catch (err) {
    // Log but never throw — the cron backstop catches any missed sends.
    console.error(
      JSON.stringify({
        event: 'outbox_enqueue_failed',
        outboxId,
        error: err instanceof Error ? err.message : String(err),
      }),
    );
  }
}
