import axios, { AxiosRequestConfig } from 'axios'
import { StaticKey } from '../@core/types/static-key.enum'
import { parseCookies } from 'nookies'
import { getCookie } from 'cookies-next/client'

interface CustomAxiosRequestConfig<TData> extends AxiosRequestConfig<TData> {
  withToken?: boolean
  lang?: string
}

const apiUrl = process.env.NEXT_PUBLIC_API_URL
const client = axios.create({ baseURL: apiUrl })

export const request = async <TResponse = any, TData = any>({
  withToken = true,
  lang,
  ...options
}: CustomAxiosRequestConfig<TData>): Promise<TResponse> => {
  const cookies = parseCookies()
  const language = cookies['NEXT_LOCALE'] || lang || 'en'

  client.defaults.headers.common['accept-language'] = language

  if (withToken) {
    const token = getCookie(StaticKey.ACCESS_TOKEN) || null

    console.log('🚀 ~ request ~ token:', token)
    if (token) {
      client.defaults.headers.common.Authorization = `Bearer ${token}`
    }
  }

  return client({ ...options }).then(data => data.data)
}
