import { BROWSER_TOKEN_KEY, backendURL, isServer } from '@/services/request/constants';
import axios, { AxiosError, AxiosResponse } from 'axios';
import { getCookie } from 'cookies-next';

const request = axios.create({
    baseURL: backendURL + '/api/v1',
    headers: {
        'Content-Type': 'application/json',
    },
});

request.interceptors.request.use(async config => {
    if (isServer()) {
        const { cookies } = await import('next/headers');
        const token = cookies().get(BROWSER_TOKEN_KEY)?.value;

        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }
    } else {
        if (getCookie(BROWSER_TOKEN_KEY)) {
            config.headers['Authorization'] = config.headers['Authorization'] || `Bearer ${getCookie(BROWSER_TOKEN_KEY)}`;
        }
    }

    return config;
});

request.interceptors.response.use(
    async (response: AxiosResponse) => {
        return response;
    },
    async (error: AxiosError) => {
        return Promise.reject(error);
    }
);

export default request;
