import axios from 'axios';

const api = axios.create({
    baseURL: 'https://cyberhawk.pushpak.cloud/api',
});

// --- 1. Request Interceptor ---
// This function runs BEFORE every single request is sent.
api.interceptors.request.use(
    (config) => {
        // Check token expiration before proceeding
        const token = localStorage.getItem('accessToken');
        const tokenTimestamp = localStorage.getItem('tokenTimestamp');
        
        if (token && tokenTimestamp) {
            const currentTime = Date.now();
            const tokenAge = currentTime - parseInt(tokenTimestamp);
            const maxTokenAge = 8 * 60 * 60 * 1000; // 8 hours in milliseconds
            
            if (tokenAge > maxTokenAge) {
                // Token has expired, logout user
                console.log('Token expired (8 hours), logging out user');
                localStorage.removeItem('accessToken');
                localStorage.removeItem('tokenTimestamp');
                window.location.href = '/login';
                return Promise.reject(new Error('Token expired'));
            }
        }
        
        // If a token exists, add it to the Authorization header
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
            console.log('Adding auth token to request:', config.url);
        } else {
            console.log('No auth token found for request:', config.url);
        }
        

        
        return config; // Continue with the request
    },
    (error) => {
        // Handle any request errors
        return Promise.reject(error);
    }
);

// --- 2. Response Interceptor ---
// This function runs AFTER a response is received.
api.interceptors.response.use(
    (response) => {
        // If the response is successful (e.g., status 200), just return it
        console.log('API Response received:', response.status, response.config.url);
        return response;
    },
    (error) => {
        // Check if the error is a 401 Unauthorized error
        if (error.response && error.response.status === 401) {
            // Check if we should skip the auth redirect (for OTP verification)
            if (error.config.headers && error.config.headers['X-Skip-Auth-Redirect']) {
                console.log('Skipping auth redirect due to X-Skip-Auth-Redirect header');
                return Promise.reject(error);
            }
            
            // This means the token is invalid or expired
            console.error("Authentication Error: Token is invalid or expired. Logging out.");
            
            // Remove the invalid token from storage
            localStorage.removeItem('accessToken');
            
            // Redirect the user to the login page
            // We use `window.location.href` to force a full page reload, clearing any old state.
            window.location.href = '/login';
        }
        
        // For all other errors, just pass them along
        return Promise.reject(error);
    }
);

// Function to set token timestamp when user logs in
export const setTokenTimestamp = () => {
    localStorage.setItem('tokenTimestamp', Date.now().toString());
    console.log('Token timestamp set for 8-hour expiration');
};

// Function to check if token is expired
export const isTokenExpired = () => {
    const token = localStorage.getItem('accessToken');
    const tokenTimestamp = localStorage.getItem('tokenTimestamp');
    
    if (!token || !tokenTimestamp) {
        return true;
    }
    
    const currentTime = Date.now();
    const tokenAge = currentTime - parseInt(tokenTimestamp);
    const maxTokenAge = 8 * 60 * 60 * 1000; // 8 hours in milliseconds
    
    return tokenAge > maxTokenAge;
};

// Function to get remaining time until token expires
export const getTokenRemainingTime = () => {
    const tokenTimestamp = localStorage.getItem('tokenTimestamp');
    
    if (!tokenTimestamp) {
        return 0;
    }
    
    const currentTime = Date.now();
    const tokenAge = currentTime - parseInt(tokenTimestamp);
    const maxTokenAge = 8 * 60 * 60 * 1000; // 8 hours in milliseconds
    
    return Math.max(0, maxTokenAge - tokenAge);
};

// Function to logout user and clear all data
export const logoutUser = () => {
    localStorage.removeItem('accessToken');
    localStorage.removeItem('tokenTimestamp');
    window.location.href = '/login';
};

export default api;