const axios = require('axios');

const MLB_API_BASE = 'https://statsapi.mlb.com/api/v1';
const TIMEOUT = 10000;

async function getPlayerStats(playerId) {
  const { data } = await axios.get(`${MLB_API_BASE}/people/${playerId}/stats`, {
    params: {
      stats: 'season',
      group: 'hitting,pitching',
      season: new Date().getFullYear(),
    },
    timeout: TIMEOUT,
  });
  return data;
}

async function getGameLog(playerId, season) {
  const yr = season || new Date().getFullYear();
  const { data } = await axios.get(`${MLB_API_BASE}/people/${playerId}/stats`, {
    params: {
      stats: 'gameLog',
      group: 'hitting,pitching',
      season: yr,
    },
    timeout: TIMEOUT,
  });
  return data;
}

async function searchPlayer(name) {
  const { data } = await axios.get(`${MLB_API_BASE}/sports/1/players`, {
    params: {
      search: name,
      season: new Date().getFullYear(),
    },
    timeout: TIMEOUT,
  });
  return data;
}

async function getTeamRoster(teamId) {
  const { data } = await axios.get(`${MLB_API_BASE}/teams/${teamId}/roster`, {
    params: {
      rosterType: 'active',
    },
    timeout: TIMEOUT,
  });
  return data;
}

async function getTodaysGames() {
  const today = new Date().toISOString().slice(0, 10);
  const { data } = await axios.get(`${MLB_API_BASE}/schedule`, {
    params: {
      sportId: 1,
      date: today,
    },
    timeout: TIMEOUT,
  });
  return data;
}

module.exports = { getPlayerStats, getGameLog, searchPlayer, getTeamRoster, getTodaysGames };
