import type { Team } from './apiResponseTypes'
import { SITE_URL } from './utilities'

export interface Player {
  bbref_id: string
  demotion_week: number
  headshot: any
  id: number
  il_return: any
  image: string
  image2: string
  injury_rating: string //could strongly type as XpYY
  last_game: string // could strongly type as XX.X IP wXXgX
  last_game2: string
  name: string
  pitcher_injury: string
  pos_1: string
  pos_2: string
  pos_3: string
  pos_4: string
  pos_5: string
  pos_6: string
  pos_7: string
  pos_8: string
  season: number
  strat_code: string
  team: Team,
  vanity_card: string
  wara: number
}

export async function fetchPlayers(seasonNumber: number): Promise<Player[]> {
  const response = await fetch(`${SITE_URL}/api/v3/players?season=${seasonNumber}`)

  const playersResponse: {
    count: number
    players: Player[]
  } = await response.json()

  return playersResponse.players
}

// TODO should/can this use team abbrev instead of id?
export async function fetchPlayersByTeam(seasonNumber: number, teamId: number): Promise<Player[]> {
  const response = await fetch(`${SITE_URL}/api/v3/players?season=${seasonNumber}&team_id=${teamId}`)

  const playersResponse: {
    count: number
    players: Player[]
  } = await response.json()

  return playersResponse.players
}

export async function fetchPlayerByName(seasonNumber: number, playerName: string): Promise<Player | undefined> {
  const response = await fetch(`${SITE_URL}/api/v3/players?season=${seasonNumber}&name=${playerName}`)

  const playersResponse: {
    count: number
    players: Player[]
  } = await response.json()

  if (playersResponse.count === 0) return undefined

  if (playersResponse.count > 1) {
    throw new Error(`playersServices.fetchPlayerByName - Return contained more than one player for name: ${playerName} in season number ${seasonNumber}`)
  }

  return playersResponse.players[0]
}
