import axios from 'axios';
import { orderToken } from './auth';
import { IService } from './types';

interface IServiceResponse {
  resStatus: number;
  resData: {
    success: boolean;
    message: string;
    data?: any;
  };
}

const callService = async ({
  baseURL,
  url,
  method,
  payload,
}: IService): Promise<IServiceResponse> => {
  let resStatus = 500;
  let resData = {
    success: false,
    message: 'Something went wrong',
  };
  const { query, body, user } = payload;
  if (!user) {
    return { resStatus, resData };
  }
  const token = orderToken(user);
  const config = {
    method,
    url,
    baseURL,
    headers: {
      authorization: `Bearer ${token}`,
    },
  };
  if (query) {
    Object.assign(config, { params: query });
  }

  if (body) {
    Object.assign(config, { data: body });
  }

  return axios(config)
    .then(({ status, data }) => {
      resStatus = status;
      resData = data;
    })
    .catch(({ response }) => {
      if (response) {
        const { status, data } = response;
        resStatus = status;
        resData = data;
      }
    })
    .then(() => ({ resStatus, resData }));
};

export = callService;
