import type { Game } from './apiResponseTypes'
import { MODERN_STAT_ERA_START, SITE_URL } from './utilities'

export async function fetchGamesBySeasonAndTeamId(seasonNumber: number, teamId: number): Promise<Game[]> {
  if (seasonNumber < MODERN_STAT_ERA_START) {
    console.warn('Cannot use games endpoint to fetch stats before season 8')
    return []
  }

  const response = await fetch(`${SITE_URL}/api/v3/games?season=${seasonNumber}&team1_id=${teamId}&team2_id=${teamId}&season_type=regular`)

  const gamesResponse: {
    count: number
    games: Game[]
  } = await response.json()

  return gamesResponse.games
}

export async function fetchGamesBySeasonAndWeek(seasonNumber: number, weekNumber: number): Promise<Game[]> {
  if (seasonNumber < MODERN_STAT_ERA_START) {
    console.warn('Cannot use games endpoint to fetch stats before season 8')
    return []
  }

  const response = await fetch(`${SITE_URL}/api/v3/games?season=${seasonNumber}&week=${weekNumber}`)

  const gamesResponse: {
    count: number
    games: Game[]
  } = await response.json()

  return gamesResponse.games
}

export async function fetchSingleGame(seasonNumber: number, weekNumber: number, gameNumber: number, homeTeamId: number, awayTeamId: number): Promise<Game | undefined> {
  if (seasonNumber < MODERN_STAT_ERA_START) {
    console.warn('Cannot use games endpoint to fetch stats before season 8')
    return undefined
  }

  const response = await fetch(`${SITE_URL}/api/v3/games?season=${seasonNumber}&week=${weekNumber}&game_num=${gameNumber}&team1_id=${homeTeamId}&team2_id=${awayTeamId}`)

  const gamesResponse: {
    count: number
    games: Game[]
  } = await response.json()

  if (gamesResponse.count !== 1) {
    throw new Error('gameService.fetchSingleGame - Expected one game, return contained none or many')
  }

  return gamesResponse.games[0]
}

// v3/games?season=9&week=1&game_num=1&team1_id=355&team2_id=361&short_output=TRUE
