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

// 마이크로서비스별 호스트 설정
const GATEWAY_HOST = 'http://kt-event-marketing-api.20.214.196.128.nip.io';
const API_HOSTS = {
  user: GATEWAY_HOST,
  event: GATEWAY_HOST,
  content: GATEWAY_HOST,
  ai: GATEWAY_HOST,
  participation: GATEWAY_HOST,
  distribution: GATEWAY_HOST,
  analytics: GATEWAY_HOST,
};

const API_VERSION = process.env.NEXT_PUBLIC_API_VERSION || 'api';

// 기본 User API 클라이언트 (Gateway 직접 연결)
const API_BASE_URL = API_HOSTS.user;

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

// Participation API 전용 클라이언트
export const participationClient: AxiosInstance = axios.create({
  baseURL: `${API_HOSTS.participation}/${API_VERSION}`,
  timeout: 90000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Distribution API 전용 클라이언트
export const distributionClient: AxiosInstance = axios.create({
  baseURL: `${API_HOSTS.distribution}`,
  timeout: 90000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 공통 Request interceptor 함수
const requestInterceptor = (config: InternalAxiosRequestConfig) => {
  console.log('🚀 API Request:', {
    method: config.method?.toUpperCase(),
    url: config.url,
    baseURL: config.baseURL,
    data: config.data,
  });

  const token = localStorage.getItem('accessToken');
  if (token && config.headers) {
    config.headers.Authorization = `Bearer ${token}`;
    console.log('🔑 Token added to request');
  }
  return config;
};

const requestErrorInterceptor = (error: AxiosError) => {
  console.error('❌ Request Error:', error);
  return Promise.reject(error);
};

// 공통 Response interceptor 함수
const responseInterceptor = (response: any) => {
  console.log('✅ API Response:', {
    status: response.status,
    url: response.config.url,
    data: response.data,
  });
  return response;
};

const responseErrorInterceptor = (error: AxiosError) => {
  console.error('❌ 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);
};

// User API Client 인터셉터 적용
apiClient.interceptors.request.use(requestInterceptor, requestErrorInterceptor);
apiClient.interceptors.response.use(responseInterceptor, responseErrorInterceptor);

// Participation API Client 인터셉터 적용
participationClient.interceptors.request.use(requestInterceptor, requestErrorInterceptor);
participationClient.interceptors.response.use(responseInterceptor, responseErrorInterceptor);

// Distribution API Client 인터셉터 적용
distributionClient.interceptors.request.use(requestInterceptor, requestErrorInterceptor);
distributionClient.interceptors.response.use(responseInterceptor, responseErrorInterceptor);

export default apiClient;
