
export const getAccessToken = () => localStorage.getItem('accessToken');

export const saveAccessToken = (token) => localStorage.setItem('accessToken', token);

export const removeTokens = () => {
    localStorage.removeItem('accessToken');
    location.href = "/";
};

const apiClient = axios.create({
    timeout: 100000,
    headers: {
        'Content-Type': 'application/json',
    },
    withCredentials: true
});

apiClient.interceptors.request.use(
    (config) => {
        const token = getAccessToken();
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        return config;
    },
    (error) => Promise.reject(error)
);

apiClient.interceptors.response.use(
    (response) => {
        const authHeader = response.headers['authorization'];
        if (authHeader?.startsWith('Bearer ')) {
            const token = authHeader.substring(7);
            saveAccessToken(token);
        }
        return response;
    },
    async (error) => {
        if (error.response) {
            const status = error.response.status;
            const responseData = error.response.data;
            let alertMessage = responseData.message;
            
            if (responseData.data && Array.isArray(responseData.data) && responseData.data.length > 0) {
                const firstError = responseData.data[0];
                if (firstError.reason) {
                    alertMessage = firstError.reason;
                }
            }
            
            if (alertMessage) {
                alert(alertMessage);
            }
            
            if (status === 401) {
                removeTokens();
                location.href = "/";
            }
            return new Promise(() => {});
        }
        return Promise.reject(error);
    }
);

export default apiClient;