import axios from 'axios';
import * as SecureStore from 'expo-secure-store';

const API_BASE_URL = process.env.EXPO_PUBLIC_API_URL;
export const KEY_TOKEN = 'auth_key';

// Create an Axios instance with default configuration
const api = axios.create({
    baseURL: API_BASE_URL,
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    },
    timeout: 10000, // 10 seconds timeout
});

// Export function to update base URL
export const setApiBaseUrl = (url: string) => {
    if (url) {
        api.defaults.baseURL = url;
        console.log(`[API] Base URL updated to: ${url}`);
    }
};

// Interceptor: Adds the token to EVERY request if it exists
api.interceptors.request.use(
    async (config) => {
        const token = await SecureStore.getItemAsync(KEY_TOKEN);
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        console.log(`[API REQUEST] ${config.method?.toUpperCase()} ${config.url}`);
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// Interceptor: Global error handling (e.g., expired token)
api.interceptors.response.use(
    (response) => response,
    async (error) => {
        const originalRequest = error.config;
        
        if (error.response) {
            const isLoginRequest = originalRequest?.url?.includes('/user/login');
            if (!(error.response.status === 401 && isLoginRequest)) {
                console.error('[API ERROR]', error.response.status, error.response.data);
            }

            // If we receive 401 (Unauthorized), we might want to force logout
            if (error.response.status === 401) {
                // TODO: Here you can add logic to redirect to login screen if needed
                await SecureStore.deleteItemAsync(KEY_TOKEN);
            }
        } else {
            console.error('[API NETWORK ERROR]', error.message);
        }
        
        return Promise.reject(error);
    }
);

export default api;