import type { AxiosError, AxiosRequestConfig, CreateAxiosDefaults } from 'axios';
import axios from 'axios';
import type { VimpResponse, VimpResult } from '../../types';

export const createVimpClient = (config?: CreateAxiosDefaults) => {
  const instance = axios.create(config);

  const vimpPost = <T>(url: string, data?: AxiosRequestConfig['data'], options?: Partial<Omit<AxiosRequestConfig, 'data'>> & { retRaw?: boolean; upload?: boolean }): Promise<VimpResponse<T>> => {
    const { retRaw, upload, ...reqConfig } = options ?? {};
    return new Promise((resolve) => {
      instance
        .post(url, data, { headers: { 'content-type': upload ? 'multipart/form-data' : 'application/json' }, ...reqConfig })
        .then((res) => {
          const resData = res.data;
          if (retRaw) {
            resolve([null, resData as T, null]);
          } else {
            resolve([null, resData.data as T, resData as VimpResult<T>]);
          }
        })
        .catch((err) => {
          resolve([err as AxiosError, null, null]);
        });
    });
  };

  return {
    instance,
    post: vimpPost,
  };
};

export const unwrapVimpResponse = <T>(resp: VimpResponse<T>) => {
  const [err, data, result] = resp;
  if (err) throw err;
  if (result) {
    const { code, msg } = result;
    if (code !== 0 && code !== 200) throw new Error(`${msg || '请求失败'}`);
  }
  return data;
};

export const vimpClient = createVimpClient({
  baseURL: `/vimp/api/client`,
});
