import axios, { AxiosRequestConfig, Method } from 'axios';
import { ApiError } from '../error/api-error';

export async function callExtImsApi<T>(
  method: Method,
  url: string | { url: string; query?: Record<string, string | number> },
  params?: Record<string, any>,
  requestParams: AxiosRequestConfig = {},
) {
  let call_url: URL;
  if (typeof url === 'string') call_url = new URL(url);
  else {
    call_url = new URL(url.url);
    if (url.query) {
      for (const [key, val] of Object.entries(url.query)) {
        if (val === undefined || val === null) continue;
        call_url.searchParams.append(key, val.toString());
      }
    }
  }
  if (method === 'GET' && params) {
    for (const [key, val] of Object.entries(params)) {
      if (val === undefined || val === null) continue;
      call_url.searchParams.append(key, val.toString());
    }
  }

  const axiosParams: AxiosRequestConfig = {
    ...(requestParams ? requestParams : {}),
    method,
    validateStatus: () => true,
    url: call_url.toString(),
    data: {
      ...(params ? params : {}),
    },
    headers: {
      'Content-Type': 'application/json',
      ...(requestParams && requestParams.headers ? requestParams.headers : {}),
    },
  };
  const res = await axios(axiosParams);
  if (res.status !== 200 && res.status !== 201) {
    let errorObject = res.data;
    if (!errorObject.message) {
      errorObject = {
        message: JSON.stringify(errorObject),
        code: 'SERVER_ERROR',
        payload: null,
      };
    }
    throw new ApiError(
      errorObject.message,
      errorObject.code,
      errorObject.payload,
    );
  }
  return res.data as T;
}
