import axios from 'axios';

// NOTE: This scope MUST match the one used in your AutoLogoutProvider
const apiRequest = {
    scopes: ["api://d82560a8-8fac-401d-9173-10668acb7dfa/access_as_user"]
};

/**
 * Sets up an Axios request interceptor to automatically acquire an MSAL token 
 * and attach it to the Authorization header before sending the request.
 * @param {object} msalInstance - The PublicClientApplication instance from MSAL.
 */
export const setupMsalAxiosInterceptor = (msalInstance) => {
    axios.interceptors.request.use(async (config) => {
        // 1. Check if user is logged in
        const accounts = msalInstance.getAllAccounts();
        
        if (accounts.length > 0) {
            // Set the account for the token request
            apiRequest.account = accounts[0];

            try {
                // 2. Attempt to acquire the token silently (fastest way)
                const response = await msalInstance.acquireTokenSilent(apiRequest);

                // 3. Attach the Access Token to the Authorization header
                config.headers.Authorization = `Bearer ${response.accessToken}`;
            } catch (error) {
                // If silent acquisition fails (e.g., token expired, or user needs interaction),
                // we allow the request to proceed without a token. The response interceptor 
                // or the AutoLogoutProvider will handle the eventual 401/logout.
                console.warn("MSAL: Silent token acquisition failed. Request sent without token.", error);
            }
        }
        
        // 4. Return the (potentially modified) config
        return config;
    }, (error) => {
        return Promise.reject(error);
    });
    
    // You should use the existing response interceptor in auth/index.js to handle 401s 
    // for non-idle requests, which should call dispatch(handleLogoutFunction()) and instance.logoutRedirect().
};