import axios, { type InternalAxiosRequestConfig, type AxiosResponse } from 'axios';
import { useAuthStore } from '@/stores/auth';
import { showToast } from 'vant';

const service = axios.create({
    baseURL: 'http://100.64.32.254:8080/api/v1', // Proxy will handle this to backend
    timeout: 10000,
});

// Request Interceptor
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        const authStore = useAuthStore();
        if (authStore.token) {
            config.headers['Authorization'] = `Bearer ${authStore.token}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// Response Interceptor
service.interceptors.response.use(
    (response: AxiosResponse) => {
        // For blob responses (file downloads), return data directly
        if (response.config.responseType === 'blob') {
            return response.data;
        }

        const res = response.data;
        // According to API docs: code 200 is success
        if (res.code !== 200) {
            showToast(res.message || 'Error');

            // Handle specific error codes if needed
            // 401: Token expired or invalid
            if (res.code === 401) {
                const authStore = useAuthStore();
                authStore.logout();
                location.reload();
            }
            return Promise.reject(new Error(res.message || 'Error'));
        }
        return res.data; // Return the actual data part directly
    },
    (error) => {
        console.error('Request Error:', error);
        showToast(error.message || 'Request Failed');
        return Promise.reject(error);
    }
);

export default service;
