import { apiFetch } from '../../utils/apiFetch'

const apiBaseUrl = import.meta.env.VITE_API_URL ?? 'http://localhost:5000'

export type LeaderboardEntry = {
  rank: number
  username: string
  totalPoints: number
  betsPlaced: number
  betsEvaluated: number
}

export type LeaderboardResult = {
  entries: LeaderboardEntry[]
  currentUserEntry: LeaderboardEntry | null
}

export async function fetchLeaderboard(
  token: string,
  competitionId: number,
): Promise<LeaderboardResult> {
  const response = await apiFetch(`${apiBaseUrl}/api/leaderboard/${competitionId}`, {
    headers: { Authorization: `Bearer ${token}` },
  })

  if (!response.ok) {
    throw new Error(`Failed to fetch leaderboard (${response.status})`)
  }

  return response.json() as Promise<LeaderboardResult>
}
