/**
 * Timer webhook helpers — time-management.
 *
 * Enqueues webhook lifecycle events onto the `webhook.deliver` QUEUE binding.
 * Consumer is defined upstream in webhooks-engine (foundation).
 */
import type { Env } from '@zync/types'

type TimerStartedPayload = {
  entryId: string
  userId: string | null
  taskId: string | null
  projectId: string
  startedAt: string
  source: string
}

type TimerStoppedPayload = {
  entryId: string
  userId: string | null
  taskId: string | null
  projectId: string
  startedAt: string
  stoppedAt: string
  durationSeconds: number | null
}

type TimerAutoPausedPayload = {
  entryId: string
  userId: string | null
  taskId: string | null
  projectId: string
  startedAt: string
  stoppedAt: string
  durationSeconds: number | null
}

type TimerWebhook =
  | { event: 'timer.started'; payload: TimerStartedPayload }
  | { event: 'timer.stopped'; payload: TimerStoppedPayload }
  | { event: 'timer.auto_paused'; payload: TimerAutoPausedPayload }

/**
 * Enqueue a timer lifecycle webhook for delivery.
 * Non-throwing: if the queue send fails it is logged but does not break the
 * primary request (best-effort delivery by design).
 */
export async function enqueueTimerWebhook(
  env: Env,
  tenantId: string,
  webhook: TimerWebhook,
): Promise<void> {
  try {
    await env.QUEUE.send({
      type: 'webhook.deliver',
      tenantId,
      event: webhook.event,
      payload: webhook.payload,
    })
  } catch (err) {
    // Non-fatal: log and continue
    console.error('[time-webhooks] Failed to enqueue webhook', webhook.event, err)
  }
}
