import axios from 'axios';
import type {
  ApiResponse,
  PageResponse,
  ParticipationRequest,
  ParticipationResponse,
  GetParticipantsParams,
} from '../types/api.types';

/**
 * Participation API Service
 * 이벤트 참여 관련 API 함수들
 * Next.js API Routes를 통해 프록시하여 CORS 문제 해결
 */

/**
 * 이벤트 참여 신청
 * POST /api/participations/{eventId}/participate
 */
export const participate = async (
  eventId: string,
  data: ParticipationRequest
): Promise<ApiResponse<ParticipationResponse>> => {
  const response = await axios.post<ApiResponse<ParticipationResponse>>(
    `/api/participations/${eventId}/participate`,
    data
  );
  return response.data;
};

/**
 * 참여자 목록 조회 (페이징)
 * GET /api/participations/{eventId}/participants
 */
export const getParticipants = async (
  params: GetParticipantsParams
): Promise<ApiResponse<PageResponse<ParticipationResponse>>> => {
  const { eventId, storeVisited, page = 0, size = 20, sort = ['createdAt,DESC'] } = params;

  const queryParams = new URLSearchParams();
  if (storeVisited !== undefined) queryParams.append('storeVisited', String(storeVisited));
  queryParams.append('page', String(page));
  queryParams.append('size', String(size));
  sort.forEach(s => queryParams.append('sort', s));

  const response = await axios.get<ApiResponse<PageResponse<ParticipationResponse>>>(
    `/api/participations/${eventId}/participants?${queryParams.toString()}`
  );
  return response.data;
};

/**
 * 특정 참여자 정보 조회
 * GET /api/participations/{eventId}/participants/{participantId}
 */
export const getParticipant = async (
  eventId: string,
  participantId: string
): Promise<ApiResponse<ParticipationResponse>> => {
  const response = await axios.get<ApiResponse<ParticipationResponse>>(
    `/api/participations/${eventId}/participants/${participantId}`
  );
  return response.data;
};

/**
 * 참여자 검색 (클라이언트 사이드 필터링용 헬퍼)
 * 실제 API는 서버 사이드 검색을 지원하지 않으므로,
 * 전체 목록을 가져와서 클라이언트에서 필터링
 */
export const searchParticipants = async (
  eventId: string,
  searchTerm: string,
  storeVisited?: boolean
): Promise<ParticipationResponse[]> => {
  // 모든 페이지 데이터 가져오기
  let allParticipants: ParticipationResponse[] = [];
  let currentPage = 0;
  let hasMore = true;

  while (hasMore) {
    const response = await getParticipants({
      eventId,
      storeVisited,
      page: currentPage,
      size: 100, // 한 번에 많이 가져오기
    });

    allParticipants = [...allParticipants, ...response.data.content];
    hasMore = !response.data.last;
    currentPage++;
  }

  // 검색어로 필터링
  if (searchTerm) {
    const term = searchTerm.toLowerCase();
    return allParticipants.filter(
      (p) =>
        p.name.toLowerCase().includes(term) ||
        p.phoneNumber.includes(term) ||
        p.email?.toLowerCase().includes(term)
    );
  }

  return allParticipants;
};

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

/**
 * 당첨자 추첨
 * POST /api/participations/{eventId}/draw-winners
 */
export const drawWinners = async (
  eventId: string,
  winnerCount: number,
  applyStoreVisitBonus?: boolean
): Promise<ApiResponse<import('../types/api.types').DrawWinnersResponse>> => {
  const response = await axios.post<ApiResponse<import('../types/api.types').DrawWinnersResponse>>(
    `/api/participations/${eventId}/draw-winners`,
    {
      winnerCount,
      applyStoreVisitBonus,
    }
  );
  return response.data;
};

/**
 * 당첨자 목록 조회
 * GET /api/participations/{eventId}/winners
 */
export const getWinners = async (
  eventId: string,
  page = 0,
  size = 20,
  sort: string[] = ['winnerRank,ASC']
): Promise<ApiResponse<PageResponse<ParticipationResponse>>> => {
  const queryParams = new URLSearchParams();
  queryParams.append('page', String(page));
  queryParams.append('size', String(size));
  sort.forEach(s => queryParams.append('sort', s));

  const response = await axios.get<ApiResponse<PageResponse<ParticipationResponse>>>(
    `/api/participations/${eventId}/winners?${queryParams.toString()}`
  );
  return response.data;
};
