import axios, { AxiosResponse } from 'axios';

import { EN_LOCALE, ES_LOCALE, Locale, defaultLocale } from '@/i18n.config';

const instance = axios.create({
  baseURL: process.env.API_HOST,
});

const responseBody = (response: AxiosResponse) => response.data;

const requests = {
  get: (url: string) => instance.get(url)
    .then(responseBody)
    .catch(() => null),
  post: (url: string, body: {}) => instance.post(url, body)
    .then(responseBody)
    .catch(() => null),
  put: (url: string, body: {}) => instance.put(url, body)
    .then(responseBody)
    .catch(() => null),
};

const formatLocale = (locale: string) => {
  if ([ES_LOCALE, EN_LOCALE].includes(locale)) {
    return locale;
  }

  return 'pt-BR';
}

const Api = {
  about: {
    getContent: (
      locale: Locale = defaultLocale
    ): Promise<any> => requests.get(`/about?locale=${formatLocale(locale)}`),
  },
  glossary: {
    getContent: (
      locale: Locale = defaultLocale
    ): Promise<any> => requests.get(`/glossaries?locale=${formatLocale(locale)}`),
  },
  quiz: {
    getContent: (
      locale: Locale = defaultLocale
    ): Promise<any> => requests.get(`/quiz?locale=${formatLocale(locale)}`),
  },
  rooms: {
    getAll: (
      locale: Locale = defaultLocale
    ): Promise<any> => requests.get(`/rooms?locale=${formatLocale(locale)}`),
    getBySlug: (
      slug: string,
      locale: Locale = defaultLocale,
    ): Promise<any> => requests.get(`/rooms/${slug}?locale=${formatLocale(locale)}`),
  },
};

export default Api;
