import { useAuthStore } from '@/stores/auth';
import axios from 'axios';
import { useRouter } from 'vue-router';

// Create axios instance with default config
const httpClient = axios.create({
    baseURL: '/v1',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json',
    }
});

// Request interceptor
httpClient.interceptors.request.use(
    config => {
        const authStore = useAuthStore();
        if (authStore.isAuthenticated && authStore.token) {
            config.headers.Authorization = `Bearer ${authStore.token}`;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// Response interceptor
httpClient.interceptors.response.use(
    response => {
        return response
    },
    error => {
        // Handle HTTP errors here
        if (error.response) {
            // Handle 401 Unauthorized
            if (error.response.status === 401) {
                const authStore = useAuthStore();
                authStore.logout();
                const router = useRouter();
                // Redirect to login page
                router.push('/login');
            }
            console.error('API Error:', error.response.status, error.response.data);
        } else if (error.request) {
            // Request made but no response received
            console.error('API Error: No response received', error.request);
        } else {
            // Something else happened
            console.error('API Error:', error.message);
        }
        return Promise.reject(error);
    }
);

export default httpClient;
