import { AxiosError } from 'axios';
import { secondsToMilliseconds } from 'date-fns';

/**
 * Incremental retry timeouts in milliseconds.
 * [0s (instant), 5s, 15s, 30s (cap)]
 */
const RETRY_TIMEOUTS: readonly number[] = [
  0,
  secondsToMilliseconds(5),
  secondsToMilliseconds(15),
  secondsToMilliseconds(30),
];

/**
 * Calculate incremental retry timeout based on attempt number.
 * Caps at the last value in RETRY_TIMEOUTS.
 *
 * @param attempt - The retry attempt number (0-indexed)
 * @returns Timeout in milliseconds
 */
export const getRetryTimeout = (attempt: number): number =>
  RETRY_TIMEOUTS[Math.min(attempt, RETRY_TIMEOUTS.length - 1)];

/**
 * Returns true when the error looks like a network failure (request sent,
 * no response received) — distinguished from HTTP errors, which have a response.
 */
export const isNetworkError = (error: unknown): boolean =>
  error instanceof AxiosError && !error.response;
