import type { AxiosProgressEvent } from 'axios';

export type UploadProgressHandler = (percent: number | null) => void;

export interface UploadProgressInput {
  loaded: number;
  total?: number;
  progress?: number;
}

const clampPercent = (raw: number): number => {
  if (!Number.isFinite(raw)) return 0;
  return Math.max(0, Math.min(100, Math.floor(raw)));
};

export function toUploadPercent(event: UploadProgressInput): number | null {
  if (typeof event.progress === 'number' && Number.isFinite(event.progress)) {
    return clampPercent(event.progress * 100);
  }
  if (
    typeof event.total === 'number' &&
    event.total > 0 &&
    typeof event.loaded === 'number' &&
    Number.isFinite(event.loaded)
  ) {
    return clampPercent((event.loaded / event.total) * 100);
  }
  return null;
}

export function createAxiosUploadProgressHandler(
  handler: UploadProgressHandler,
): (event: AxiosProgressEvent) => void {
  return (event) => {
    handler(toUploadPercent(event));
  };
}