import { apiClient } from '@/shared/api';
import type {
  GetEventsRequest,
  GetEventsResponse,
  EventDetail,
  ApiResponse,
  SelectObjectiveRequest,
  EventCreatedResponse,
  AiRecommendationRequest,
  JobAcceptedResponse,
  ImageGenerationRequest,
  ImageGenerationResponse,
  UpdateEventRequest,
  SelectChannelsRequest,
  SelectImageRequest,
} from '../model/types';

/**
 * Event API 기본 경로
 *
 * 참고: apiClient는 기본적으로 user-service(8081)를 가리키므로
 * 별도의 event API 클라이언트를 사용하는 것이 좋습니다.
 *
 * 현재는 apiClient를 사용하되, baseURL을 오버라이드합니다.
 */
const EVENT_API_BASE = '/api/v1/events';
const EVENT_HOST = 'http://kt-event-marketing-api.20.214.196.128.nip.io';

/**
 * Event Service용 API 클라이언트
 * Event Service는 별도 포트(8080)에서 실행되므로 별도 클라이언트 생성
 */
import axios from 'axios';

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

const eventApiClient = axios.create({
  baseURL: `${EVENT_HOST}/api/${API_VERSION}`,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: false, // CORS 설정
});

// Request interceptor - JWT 토큰 추가
eventApiClient.interceptors.request.use(
  (config) => {
    console.log('🚀 Event 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 Event API request');
    }
    return config;
  },
  (error) => {
    console.error('❌ Event API Request Error:', error);
    return Promise.reject(error);
  }
);

// Response interceptor - 에러 처리
eventApiClient.interceptors.response.use(
  (response) => {
    console.log('✅ Event API Response:', {
      status: response.status,
      url: response.config.url,
      data: response.data,
    });
    return response;
  },
  (error) => {
    console.error('❌ Event 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);
  }
);

/**
 * Event API Service
 * 이벤트 관리 API
 */
export const eventApi = {
  /**
   * 이벤트 목록 조회
   */
  getEvents: async (params?: GetEventsRequest): Promise<GetEventsResponse> => {
    console.log('📞 eventApi.getEvents 호출', params);
    const response = await eventApiClient.get<GetEventsResponse>(EVENT_API_BASE, {
      params,
    });
    return response.data;
  },

  /**
   * 이벤트 상세 조회
   */
  getEvent: async (eventId: string): Promise<ApiResponse<EventDetail>> => {
    console.log('📞 eventApi.getEvent 호출', eventId);
    const response = await eventApiClient.get<ApiResponse<EventDetail>>(
      `${EVENT_API_BASE}/${eventId}`
    );
    return response.data;
  },

  /**
   * 이벤트 생성 (목적 선택)
   */
  createEvent: async (
    data: SelectObjectiveRequest
  ): Promise<ApiResponse<EventCreatedResponse>> => {
    console.log('📞 eventApi.createEvent 호출', data);
    const response = await eventApiClient.post<ApiResponse<EventCreatedResponse>>(
      `${EVENT_API_BASE}/objectives`,
      data
    );
    return response.data;
  },

  /**
   * 이벤트 삭제
   */
  deleteEvent: async (eventId: string): Promise<ApiResponse<void>> => {
    console.log('📞 eventApi.deleteEvent 호출', eventId);
    const response = await eventApiClient.delete<ApiResponse<void>>(
      `${EVENT_API_BASE}/${eventId}`
    );
    return response.data;
  },

  /**
   * 이벤트 배포
   */
  publishEvent: async (eventId: string): Promise<ApiResponse<void>> => {
    console.log('📞 eventApi.publishEvent 호출', eventId);
    const response = await eventApiClient.post<ApiResponse<void>>(
      `${EVENT_API_BASE}/${eventId}/publish`
    );
    return response.data;
  },

  /**
   * 이벤트 종료
   */
  endEvent: async (eventId: string): Promise<ApiResponse<void>> => {
    console.log('📞 eventApi.endEvent 호출', eventId);
    const response = await eventApiClient.post<ApiResponse<void>>(
      `${EVENT_API_BASE}/${eventId}/end`
    );
    return response.data;
  },

  /**
   * AI 추천 요청
   */
  requestAiRecommendations: async (
    eventId: string,
    data: AiRecommendationRequest
  ): Promise<ApiResponse<JobAcceptedResponse>> => {
    console.log('📞 eventApi.requestAiRecommendations 호출', eventId, data);
    const response = await eventApiClient.post<ApiResponse<JobAcceptedResponse>>(
      `${EVENT_API_BASE}/${eventId}/ai-recommendations`,
      data
    );
    return response.data;
  },

  /**
   * 이미지 생성 요청
   */
  requestImageGeneration: async (
    eventId: string,
    data: ImageGenerationRequest
  ): Promise<ApiResponse<ImageGenerationResponse>> => {
    console.log('📞 eventApi.requestImageGeneration 호출', eventId, data);
    const response = await eventApiClient.post<ApiResponse<ImageGenerationResponse>>(
      `${EVENT_API_BASE}/${eventId}/images`,
      data
    );
    return response.data;
  },

  /**
   * 이벤트 수정
   */
  updateEvent: async (
    eventId: string,
    data: UpdateEventRequest
  ): Promise<ApiResponse<EventDetail>> => {
    console.log('📞 eventApi.updateEvent 호출', eventId, data);
    const response = await eventApiClient.put<ApiResponse<EventDetail>>(
      `${EVENT_API_BASE}/${eventId}`,
      data
    );
    return response.data;
  },

  /**
   * 배포 채널 선택
   */
  selectChannels: async (
    eventId: string,
    data: SelectChannelsRequest
  ): Promise<ApiResponse<void>> => {
    console.log('📞 eventApi.selectChannels 호출', eventId, data);
    const response = await eventApiClient.put<ApiResponse<void>>(
      `${EVENT_API_BASE}/${eventId}/channels`,
      data
    );
    return response.data;
  },

  /**
   * 이미지 선택
   */
  selectImage: async (
    eventId: string,
    imageId: string,
    data: SelectImageRequest
  ): Promise<ApiResponse<void>> => {
    console.log('📞 eventApi.selectImage 호출', eventId, imageId, data);
    const response = await eventApiClient.put<ApiResponse<void>>(
      `${EVENT_API_BASE}/${eventId}/images/${imageId}/select`,
      data
    );
    return response.data;
  },
};

export default eventApi;
