import type { JournalPhase } from './storage.js';

export const MAX_SUBMISSION_READY_WAIT_MS = 15_000;

export type SubmissionRecovery = 'safe-before-submit' | 'ambiguous-no-resend' | 'submitted-no-resend' | 'terminal';

export function submissionRecovery(phase: JournalPhase | null | undefined): SubmissionRecovery {
  switch (phase) {
    case 'submission-started': return 'ambiguous-no-resend';
    case 'submitted': return 'submitted-no-resend';
    case 'completed':
    case 'failed': return 'terminal';
    case 'starting':
    case 'tab-created':
    case undefined:
    case null: return 'safe-before-submit';
  }
}

export function boundedSubmissionReadyWaitMs(commandDeadline: string, nowMs = Date.now()): number {
  const remaining = Date.parse(commandDeadline) - nowMs;
  if (!Number.isFinite(remaining) || remaining <= 0) return 1;
  return Math.max(1, Math.min(MAX_SUBMISSION_READY_WAIT_MS, remaining));
}
