import type { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
import { safeJsonTransformResponse } from '../request/json';

export type ServiceRequestResult<T> =
  | {
      data: T;
      error: null;
      response: AxiosResponse<App.Service.Response<unknown>>;
    }
  | {
      data: null;
      error: AxiosError<App.Service.Response<unknown>>;
      response: AxiosResponse<App.Service.Response<unknown>> | undefined;
    };

export const safeJsonRequestConfig: Pick<AxiosRequestConfig, 'transformResponse'> = {
  transformResponse: [safeJsonTransformResponse]
};

export function normalizeStringId(id: string | number) {
  return String(id);
}

export function normalizeNullableStringId(id: string | number | null | undefined) {
  if (id === null || id === undefined || id === '') {
    return null;
  }

  return String(id);
}

export function mapServiceResult<TInput, TOutput>(
  result: ServiceRequestResult<TInput>,
  mapper: (data: TInput) => TOutput
): ServiceRequestResult<TOutput> {
  if (result.error || result.data === null) {
    return result as ServiceRequestResult<TOutput>;
  }

  return {
    ...result,
    data: mapper(result.data)
  };
}
