import fetch from "node-fetch";

// API constants
const API_KEY = "0c659161aae51ff51a6c0c41c8a591b5";
const API_HOST = "v3.football.api-sports.io";
const ROUTE_LIST = {
    LEAGUE: "league",
    PLAYER_LIST: "player-list",
};

/**
 * Get league list
 *
 * @returns - League list
 */
 async function getLeague(leagueName) {
    return await requestApi(ROUTE_LIST.LEAGUE, { leagueName });
}

/**
 * Get player list
 *
 * @returns - League list
 */
async function getPlayerList(leagueId, seasonYear) {
    return await requestApi(ROUTE_LIST.PLAYER_LIST, { leagueId, seasonYear });
}

/**
 * Request api in fonction of route and params
 *
 * @param string route - Route requested
 * @param object paramList - List of params used by route
 *
 * @returns - The API response
 */
async function requestApi(route, paramList) {
    var promise = new Promise((resolve, reject) => {
        const { headers, method, url } = getApiParamList(route, paramList);
        fetch(url, { headers, method }).then((response) => {
            response
                .json()
                .then((data) => (response.ok ? resolve(data) : reject(data)));
        });
    });

    return await promise.then(
        (data) => data.response,
        (err) => console.log(err)
    );
}

/**
 * Get all params used by route
 *
 * @param string route - Route requested
 * @param object paramList - List of params used by route
 *
 * @returns - List of params used to requested API (url, method, headers, apiKeys...)
 */
function getApiParamList(route, paramList) {
    let httpOptions = {
        headers: {
            "x-rapidapi-host": API_HOST,
            "x-rapidapi-key": API_KEY,
            "Content-Type": "application/json",
        },
    };

    switch (route) {
        case ROUTE_LIST.PLAYER_LIST:
            httpOptions.method = "GET";
            httpOptions.url = `https://v3.football.api-sports.io/players?league=${paramList.leagueId}&season=${paramList.seasonYear}`;
            break;
        case ROUTE_LIST.LEAGUE:
            httpOptions.method = "GET";
            httpOptions.url = `https://v3.football.api-sports.io/leagues?name=${paramList.leagueName}`;
            break;
    }
    return httpOptions;
}


export { getLeague, getPlayerList };