import axios from 'axios';
import { InteractionRequiredAuthError } from "@azure/msal-browser";

// ⚠️ UPDATE THIS SCOPE if needed
const apiRequest = {
    scopes: ["api://d82560a8-8fac-401d-9173-10668acb7dfa/access_as_user"]
};

/**
 * Sets up an Axios interceptor to acquire an MSAL token and handle 401 errors.
 */
export const setupMsalAxiosInterceptor = (msalInstance, dispatch, handleLogoutFunction) => {
    
    // REQUEST Interceptor: Attach the token
    axios.interceptors.request.use(async (config) => {
        const accounts = msalInstance.getAllAccounts();
        
        if (accounts.length > 0) {
            apiRequest.account = accounts[0];

            try {
                // Attempt to acquire the token silently
                const response = await msalInstance.acquireTokenSilent(apiRequest);
                config.headers.Authorization = `Bearer ${response.accessToken}`;
            } catch (error) {
                if (error instanceof InteractionRequiredAuthError) {
                    console.warn("MSAL: Silent token acquisition failed. Request sent without token.");
                } else {
                    console.error("MSAL: Token acquisition failed.", error);
                }
            }
        }
        
        // Keep your custom header
        config.headers['X-Authorization'] = process.env.REACT_APP_API_KEY; 
        return config;
    }, (error) => {
        return Promise.reject(error);
    });

    // RESPONSE Interceptor: Handle 401 Unauthorized
    axios.interceptors.response.use(
        (response) => response,
        async (error) => {
            if (error.response && error.response.status === 401) {
                console.error("401 Unauthorized received. Forcing MSAL logout.");
                
                // 1. Clear Redux/local storage state
                await dispatch(handleLogoutFunction());
                
                // 2. Clear MSAL session and redirect to login
                msalInstance.logoutRedirect();
            } 
            
            return Promise.reject(error);
        }
    );
};