import axios from 'axios'
import { getAuthTokens } from './others.js'
import { getSession } from './sessionUtils.js'

const apiUrl = import.meta.env.ENV_API_URL;
const apiCommonUrl = import.meta.env.ENV_API_URL_COMMON;
const subDirectory = import.meta.env.ENV_COMMON_BASE_URL;
const EmailApiUrl = import.meta.env.ENV_EMAIL_API;

const axiosInstance = axios.create({ baseURL: apiUrl })
const axiosCommonInstance = axios.create({
    baseURL: apiCommonUrl,
});
const addAuthHeader = async (config) => {
    try {
        const tokens = getAuthTokens();

        console.log(tokens, 'tokens')

        if (tokens && tokens.accessToken) {
            config.headers['Authorization'] = `Bearer ${tokens?.accessToken}`
        } else {
            console.warn('No access token available.')
        }

        const mobileNo = await getSession('MobileNo');
        const userId = await getSession('UserId');

        if (mobileNo && userId) {
            config.headers['MobileNo'] = decryptedUser.MobileNo
        } else {
            console.warn('MobileNo not found in decrypted data.')
            config.headers['MobileNo'] = '1000000001'
        }

    } catch (error) {
        console.error('Error in addAuthHeader:', error)
    }

    return config
}

axiosInstance.interceptors.request.use(addAuthHeader, (error) => Promise.reject(error))
axiosCommonInstance.interceptors.request.use(addAuthHeader, (error) => {console.error('Error in request interceptor:', error);return Promise.reject(error)});
const responseErrorHandler = async (error, axiosInstance) => {
    if (error.response && error.response.status === 401) {
        console.warn('Your session has expired. or Unauthorized')

        try {
            const userId = getSession('UserId');
            if (userId) {
                error.config.headers['Authorization'] = `Bearer ${newAccessToken}`
                return axiosInstance.request(error.config)
            } else {
                throw new Error('Failed in Logging Out.')
            }
        } catch (error) {
            console.error('Logging out...', error)
            return Promise.reject(error)
        }
    }
    return Promise.reject(error)
}

axiosInstance.interceptors.response.use(
    (response) => response,
    (error) => responseErrorHandler(error, axiosInstance)
)


export { axiosInstance ,axiosCommonInstance};









