/**
 * Calculate the cutoff timestamp for workflow processing based on backoffHours.
 */

import { BACKOFF_NEVER_REPROCESS } from './constants';

/**
 * Calculate the cutoff timestamp for workflow processing based on backoffHours.
 * If backoffHours is BACKOFF_NEVER_REPROCESS (-1), returns epoch (1970-01-01)
 * to ensure records are never reprocessed once they have any processing record.
 */
export function calculateCutoffTimestamp(backoffHours: number): string {
  // Validate input - must be a finite number or the special BACKOFF_NEVER_REPROCESS value
  if (
    !Number.isFinite(backoffHours) &&
    backoffHours !== BACKOFF_NEVER_REPROCESS
  ) {
    throw new Error(
      'backoffHours must be a finite number or BACKOFF_NEVER_REPROCESS',
    );
  }

  // Reject negative values other than BACKOFF_NEVER_REPROCESS
  if (backoffHours < 0 && backoffHours !== BACKOFF_NEVER_REPROCESS) {
    throw new Error(
      'backoffHours must be non-negative or BACKOFF_NEVER_REPROCESS',
    );
  }

  if (backoffHours === BACKOFF_NEVER_REPROCESS) {
    // Use epoch - any record that was ever processed will have processedAt >= 0
    return new Date(0).toISOString();
  }

  // Use millisecond arithmetic for DST-safe calculation
  return new Date(Date.now() - backoffHours * 60 * 60 * 1000).toISOString();
}
