import axios, { AxiosInstance } from 'axios';

// Use Next.js API proxy to bypass CORS issues
const CONTENT_API_BASE_URL = '/api/content';

export const contentApiClient: AxiosInstance = axios.create({
  baseURL: CONTENT_API_BASE_URL,
  timeout: 120000, // 이미지 생성은 시간이 오래 걸릴 수 있으므로 120초
  headers: {
    'Content-Type': 'application/json',
  },
});

// Request interceptor
contentApiClient.interceptors.request.use(
  (config) => {
    console.log('🎨 Content 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}`;
    }
    return config;
  },
  (error) => {
    console.error('❌ Content API Request Error:', error);
    return Promise.reject(error);
  }
);

// Response interceptor
contentApiClient.interceptors.response.use(
  (response) => {
    console.log('✅ Content API Response:', {
      status: response.status,
      url: response.config.url,
      data: response.data,
    });
    return response;
  },
  (error) => {
    console.error('❌ Content API Error:', {
      message: error.message,
      status: error.response?.status,
      url: error.config?.url,
      data: error.response?.data,
    });
    return Promise.reject(error);
  }
);

// Types
export interface GenerateImagesRequest {
  eventId: string;
  eventTitle: string;
  eventDescription: string;
  industry?: string;
  location?: string;
  trends?: string[];
  styles: ('SIMPLE' | 'FANCY' | 'TRENDY')[];
  platforms: ('INSTAGRAM' | 'NAVER' | 'KAKAO')[];
}

export interface JobInfo {
  id: string;
  eventId: string;
  jobType: string;
  status: 'PENDING' | 'PROCESSING' | 'COMPLETED' | 'FAILED';
  progress: number;
  resultMessage?: string;
  errorMessage?: string;
  createdAt: string;
  updatedAt: string;
}

export interface ImageInfo {
  id: number;
  eventId: string;
  style: 'SIMPLE' | 'FANCY' | 'TRENDY';
  platform: 'INSTAGRAM' | 'NAVER' | 'KAKAO';
  cdnUrl: string;
  prompt: string;
  selected: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface ContentInfo {
  id: number;
  eventId: string;
  eventTitle: string;
  eventDescription: string;
  images: ImageInfo[];
  createdAt: string;
  updatedAt: string;
}

// API Functions
export const contentApi = {
  // 이미지 생성 (Next.js API proxy 사용)
  generateImages: async (request: GenerateImagesRequest): Promise<JobInfo> => {
    const response = await contentApiClient.post<JobInfo>('/images/generate', request);
    return response.data;
  },

  // Job 상태 조회 (Next.js API proxy 사용)
  getJobStatus: async (jobId: string): Promise<JobInfo> => {
    const response = await contentApiClient.get<JobInfo>(`/images/jobs/${jobId}`);
    return response.data;
  },

  // 이벤트별 콘텐츠 조회
  getContentByEventId: async (eventId: string): Promise<ContentInfo> => {
    const response = await contentApiClient.get<ContentInfo>(`/events/${eventId}`);
    return response.data;
  },

  // 이미지 목록 조회 (Next.js API proxy 사용)
  getImages: async (
    eventId: string,
    style?: 'SIMPLE' | 'FANCY' | 'TRENDY',
    platform?: 'INSTAGRAM' | 'NAVER' | 'KAKAO'
  ): Promise<ImageInfo[]> => {
    const params = new URLSearchParams();
    if (style) params.append('style', style);
    if (platform) params.append('platform', platform);

    const response = await contentApiClient.get<ImageInfo[]>(
      `/events/${eventId}/images${params.toString() ? `?${params.toString()}` : ''}`
    );
    return response.data;
  },

  // 특정 이미지 조회
  getImageById: async (imageId: number): Promise<ImageInfo> => {
    const response = await contentApiClient.get<ImageInfo>(`/api/v1/content/images/${imageId}`);
    return response.data;
  },

  // 이미지 삭제
  deleteImage: async (imageId: number): Promise<void> => {
    await contentApiClient.delete(`/api/v1/content/images/${imageId}`);
  },

  // 이미지 재생성
  regenerateImage: async (imageId: number, newPrompt?: string): Promise<JobInfo> => {
    const response = await contentApiClient.post<JobInfo>(
      `/api/v1/content/images/${imageId}/regenerate`,
      { imageId, newPrompt }
    );
    return response.data;
  },
};

export default contentApi;
