import axios, { AxiosInstance, AxiosResponse } from 'axios';

const Axios: AxiosInstance = axios.create({
    baseURL: '/',
    withCredentials: false,
    headers: {
        Accept: 'application/json; charset=utf-8',
        'Content-Type': 'application/json; charset=utf-8',
        'X-Requested-With': 'XMLHttpRequest',
    },
});

/* Allows Us To Authorized Api Request If Authenticated Using Web Middleware */
Axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

// Response interceptor for nonce handling and error handling
Axios.interceptors.response.use(
    (response: AxiosResponse) => {
        // replace old nonce
        if (response.headers['X-WP-Nonce']) {
            window.$appConfig.nonce = response.headers['X-WP-Nonce'];
        }

        return response;
    },
    (error) => {
        // Handle 401 errors globally
        if (error.response?.status === 401) {
            // Import notification store dynamically to avoid circular imports
            import('../admin/stores/useNotificationStore').then(({ useNotificationStore }) => {
                const { addNotification } = useNotificationStore();
                addNotification({
                    message: 'Authentication failed. Please check your connection.',
										link: {
											label: 'Check',
											url: '/wp-admin/admin.php?page=boostsite_ai_content_generator#/settings',
										},
                    type: 'danger',
                }, 15);
            });
        }

        // Always reject the promise
        return Promise.reject(error);
    }
);

Axios.interceptors.request.use((config: any) => {
    // set nonce
    config.headers['X-WP-Nonce'] = window.$appConfig.nonce;

    return config;
});

export default Axios;
