import axios from 'axios';
import { getApiBaseUrl } from './apiConfig';

// API 베이스 URL (통합 설정 사용)
const API_BASE_URL = getApiBaseUrl();

const chatbotApi = axios.create({
  baseURL: API_BASE_URL,
  timeout: 60000, // 60초 (AI 분석 시간 고려)
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  withCredentials: false,
});

// ==================== Types ====================

export type MessageType = 'BUY' | 'SELL' | 'HOLD' | 'INFO';

export interface IndicatorValues {
  rsi?: number;
  macd?: number;
  macdSignal?: number;
  macdHistogram?: number;
  bollingerUpper?: number;
  bollingerMiddle?: number;
  bollingerLower?: number;
  ma5?: number;
  ma20?: number;
  ma60?: number;
  volume?: number;
}

export interface ChatbotMessage {
  id: number;
  configId: number;
  symbol: string;
  symbolName: string;
  messageType: MessageType;
  title: string;
  content: string;
  price?: number;
  analysisData?: Record<string, any>;
  indicators?: IndicatorValues;
  readStatus: boolean;
  createdAt: string;
}

export interface ChatbotConfig {
  id?: number;
  userId: number;
  enabled: boolean;
  scheduleType: 'CRON' | 'INTERVAL';
  cronExpression?: string;
  intervalMinutes?: number;
  candleInterval?: string;
  strategyConditions?: Record<string, any>;
  createdAt?: string;
  updatedAt?: string;
}

export interface ChatbotScheduleLog {
  id: number;
  configId: number;
  executedAt: string;
  symbolsAnalyzed: number;
  messagesCreated: number;
  success: boolean;
  errorMessage?: string;
}

export interface ChatbotStats {
  totalMessages: number;
  unreadCount: number;
  messageTypeCount: {
    BUY: number;
    SELL: number;
    HOLD: number;
    INFO: number;
  };
}

export interface PageResponse<T> {
  content: T[];
  totalElements: number;
  totalPages: number;
  size: number;
  number: number;
}

// ==================== API Functions ====================

// ========== 설정 관리 ==========

/**
 * 챗봇 설정 조회
 */
export const getChatbotConfig = (userId: number = 1) => {
  return chatbotApi.get<ChatbotConfig>(`/chatbot/config?userId=${userId}`);
};

/**
 * 챗봇 설정 저장/수정
 */
export const saveChatbotConfig = (config: ChatbotConfig) => {
  return chatbotApi.put<ChatbotConfig>('/chatbot/config', config);
};

/**
 * 챗봇 활성화/비활성화 토글
 */
export const toggleChatbotEnabled = (userId: number = 1) => {
  return chatbotApi.post<ChatbotConfig>('/chatbot/config/toggle', { userId });
};

/**
 * 챗봇 설정 삭제
 */
export const deleteChatbotConfig = (userId: number = 1) => {
  return chatbotApi.delete(`/chatbot/config?userId=${userId}`);
};

// ========== 메시지 관리 ==========

/**
 * 메시지 목록 조회 (페이징)
 */
export const getChatbotMessages = (params: {
  userId?: number;
  page?: number;
  size?: number;
  messageType?: MessageType | 'ALL';
  symbol?: string;
}) => {
  const { userId = 1, page = 0, size = 20, messageType, symbol } = params;
  
  const queryParams: Record<string, any> = {
    userId,
    page,
    size,
  };
  
  if (messageType && messageType !== 'ALL') {
    queryParams.messageType = messageType;
  }
  
  if (symbol) {
    queryParams.symbol = symbol;
  }
  
  return chatbotApi.get<PageResponse<ChatbotMessage>>('/chatbot/messages', {
    params: queryParams,
  });
};

/**
 * 메시지 상세 조회
 */
export const getChatbotMessage = (messageId: number) => {
  return chatbotApi.get<ChatbotMessage>(`/chatbot/messages/${messageId}`);
};

/**
 * 종목별 메시지 조회
 */
export const getChatbotMessagesBySymbol = (
  symbol: string,
  userId: number = 1,
  page: number = 0,
  size: number = 20
) => {
  return chatbotApi.get<PageResponse<ChatbotMessage>>(
    `/chatbot/messages/symbol/${symbol}`,
    {
      params: { userId, page, size },
    }
  );
};

/**
 * 읽지 않은 메시지 조회
 */
export const getUnreadMessages = (userId: number = 1) => {
  return chatbotApi.get<ChatbotMessage[]>('/chatbot/messages/unread', {
    params: { userId },
  });
};

/**
 * 메시지 읽음 처리
 */
export const markMessageAsRead = (messageId: number) => {
  return chatbotApi.post(`/chatbot/messages/${messageId}/read`);
};

/**
 * 여러 메시지 읽음 처리
 */
export const markMultipleMessagesAsRead = (messageIds: number[]) => {
  return chatbotApi.post('/chatbot/messages/read-multiple', messageIds);
};

/**
 * 메시지 삭제
 */
export const deleteChatbotMessage = (messageId: number) => {
  return chatbotApi.delete(`/chatbot/messages/${messageId}`);
};

/**
 * 전체 메시지 삭제
 */
export const clearAllMessages = (userId: number = 1) => {
  return chatbotApi.post('/chatbot/messages/clear', null, {
    params: { userId },
  });
};

// ========== 스케줄 제어 ==========

/**
 * 수동 분석 실행
 */
export const triggerManualAnalysis = () => {
  return chatbotApi.post<{ status: string; message: string }>(
    '/chatbot/schedule/trigger'
  );
};

/**
 * 스케줄 상태 조회
 */
export const getChatbotScheduleStatus = () => {
  return chatbotApi.get<{
    enabled: boolean;
    analyzing: boolean;
    message: string;
  }>('/chatbot/schedule/status');
};

/**
 * 스케줄 실행 로그 조회 (페이징)
 */
export const getChatbotScheduleLogs = (
  userId: number = 1,
  page: number = 0,
  size: number = 20
) => {
  return chatbotApi.get<PageResponse<ChatbotScheduleLog>>(
    '/chatbot/schedule/logs',
    {
      params: { userId, page, size },
    }
  );
};

// ========== 통계 ==========

/**
 * 챗봇 통계 정보 조회
 */
export const getChatbotStats = (userId: number = 1) => {
  return chatbotApi.get<ChatbotStats>('/chatbot/stats', {
    params: { userId },
  });
};

// ==================== Export ====================

export default chatbotApi;
