import axios, { AxiosInstance, AxiosError, InternalAxiosRequestConfig } from 'axios';

// Next.js API Proxy를 통해 Analytics API 호출 (CORS 회피)
const ANALYTICS_PROXY_BASE = '/api/analytics';

export const analyticsClient: AxiosInstance = axios.create({
  baseURL: ANALYTICS_PROXY_BASE,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Request interceptor - JWT 토큰 추가
analyticsClient.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    console.log('🚀 Analytics API Request:', {
      method: config.method?.toUpperCase(),
      url: config.url,
      baseURL: config.baseURL,
      params: config.params,
    });

    const token = localStorage.getItem('accessToken');
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
      console.log('🔑 Token added to analytics request');
    }
    return config;
  },
  (error: AxiosError) => {
    console.error('❌ Analytics Request Error:', error);
    return Promise.reject(error);
  }
);

// Response interceptor - 에러 처리
analyticsClient.interceptors.response.use(
  (response) => {
    console.log('✅ Analytics API Response:', {
      status: response.status,
      url: response.config.url,
      data: response.data,
    });
    return response;
  },
  (error: AxiosError) => {
    console.error('❌ Analytics API Error:', {
      message: error.message,
      status: error.response?.status,
      statusText: error.response?.statusText,
      url: error.config?.url,
      data: error.response?.data,
    });

    if (error.response?.status === 401) {
      console.warn('🔒 401 Unauthorized - Redirecting to login');
      localStorage.removeItem('accessToken');
      if (typeof window !== 'undefined') {
        window.location.href = '/login';
      }
    }
    return Promise.reject(error);
  }
);

export default analyticsClient;
