import Axios, { InternalAxiosRequestConfig } from 'axios';

import { env } from '../config/env';
import { Cookie } from './cookieClient';
import Swal from 'sweetalert2';
import { refreshToken } from '../features/auth/api/refreshToken';
import { queryClient } from './reactQuery';

function authRequestInterceptor(config: InternalAxiosRequestConfig) {
    if (config.headers) {
        config.headers.Accept = 'application/json';
    }

    const token = Cookie.getAccessToken();
    if (token) {
        config.headers.authorization = `Bearer ${token}`;
    }

    return config;
}

export const api = Axios.create({
    baseURL: env.API_URL,
});

api.interceptors.request.use(authRequestInterceptor);
api.interceptors.response.use(
    (response) => {
        return response.data;
    },
    async (error) => {
        const message = error.response?.data?.error || error.response?.data?.message || error.message;
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: message,
        });

        // refresh token
        const originalRequest = error.config;
        if (error.response?.status == 403 && !originalRequest._retry) {
            originalRequest._retry = true;

            try {
                const refreshTokenPromise = refreshToken({
                    refresh_token: Cookie.getRefreshToken() || '',
                });

                const { token, refresh_token } = await refreshTokenPromise;

                Cookie.setAccessToken(token);
                Cookie.setRefreshToken(refresh_token);

                originalRequest.headers.authorization = `Bearer ${token}`;

                return api(originalRequest);
            } catch (error) {
                Cookie.clearTokens();
                queryClient.clear();
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Session expired. Please login again.',
                });
            }
        }

        return Promise.reject(error);
    }
);
