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

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

export type BetResponse = {
  matchId: number
  homeScore: number
  awayScore: number
  points: number | null
}

export async function fetchCompetitionsWithBets(token: string): Promise<number[]> {
  const response = await apiFetch(`${apiBaseUrl}/api/bet/competitions`, {
    headers: { Authorization: `Bearer ${token}` },
  })

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

  return response.json() as Promise<number[]>
}

export async function fetchBets(token: string, competitionId: number): Promise<BetResponse[]> {
  const response = await apiFetch(`${apiBaseUrl}/api/bet?competitionId=${competitionId}`, {
    headers: { Authorization: `Bearer ${token}` },
  })

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

  return response.json() as Promise<BetResponse[]>
}

export type MatchBetStats = {
  matchId: number
  totalBets: number
  homeWinPercent: number
  drawPercent: number
  awayWinPercent: number
  avgHomeScore: number
  avgAwayScore: number
  topPickHomeScore: number
  topPickAwayScore: number
  topPickCount: number
}

export async function fetchMatchBetStats(token: string, matchId: number): Promise<MatchBetStats> {
  const response = await apiFetch(`${apiBaseUrl}/api/bet/match/${matchId}/stats`, {
    headers: { Authorization: `Bearer ${token}` },
  })

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

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

export async function upsertBet(
  token: string,
  matchId: number,
  homeScore: number,
  awayScore: number,
): Promise<BetResponse> {
  const response = await apiFetch(`${apiBaseUrl}/api/bet/${matchId}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
    body: JSON.stringify({ homeScore, awayScore }),
  })

  if (!response.ok) {
    const data = (await response.json()) as { message?: string } | undefined
    throw new Error(data?.message ?? `Failed to save bet (${response.status})`)
  }

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