import { api } from './api';
import { API_ENDPOINTS } from '@/utils/constants';
import {
  PlayGameRequest,
  PlayGameResponse,
  Ticket,
  ApiResponse,
  PaginatedResponse
} from '@/types';

export const gameService = {
  // Play the game with a ticket code
  play: async (ticketCode: string): Promise<PlayGameResponse> => {
    const response = await api.post<ApiResponse<PlayGameResponse>>(
      API_ENDPOINTS.GAME.PLAY,
      { ticketCode }
    );
    return response.data!;
  },

  // Get user's tickets
  getMyTickets: async (page = 1, limit = 10): Promise<PaginatedResponse<Ticket>> => {
    const response = await api.get<any>(
      `${API_ENDPOINTS.GAME.MY_TICKETS}?page=${page}&limit=${limit}`
    );

    // Le backend retourne une structure imbriquée
    // { success: true, data: { tickets: [...], pagination: {...} } }
    if (response.data && response.data.tickets && response.data.pagination) {
      return {
        data: response.data.tickets,
        total: response.data.pagination.total,
        page: response.data.pagination.page,
        limit: response.data.pagination.limit,
        totalPages: response.data.pagination.totalPages,
      };
    }

    // Fallback si la structure est différente
    return response.data!;
  },

  // Get ticket details by ID
  getTicketDetails: async (ticketId: string): Promise<Ticket> => {
    const response = await api.get<ApiResponse<Ticket>>(
      API_ENDPOINTS.GAME.TICKET_DETAILS(ticketId)
    );
    return response.data!;
  },
};
