import axios from "axios";

const vite_url = import.meta.env.VITE_URL;

export const apiAxios = axios.create({
    baseURL: `${vite_url}/api`
});
apiAxios.defaults.headers.post['Accept'] = 'application/json; charset=UTF-8';

export function isInClub(userinfo, clubId) {
    return userinfo?.groups.filter((g => g.startsWith("/club/"))).map(g => g.split("/")[2]).map(g => Number(g.split("-")[0])).includes(clubId)
}

export function isClubAdmin(userinfo) {
    return userinfo?.roles?.includes("club_president") || userinfo?.roles?.includes("club_respo_intra")
        || userinfo?.roles?.includes("club_secretaire") || userinfo?.roles?.includes("club_tresorier");
}


export const errFormater = (data, msg) => {
    if (typeof data.response.data === 'string' || data.response.data instanceof String)
        return `${msg} (${data.response.statusText}: ${data.response.data}) 😕`
    return `${msg} (${data.response.statusText}: ${JSON.stringify(data.response.data)}) 😕`
}

export function getCategoryFormBirthDate(birth_date, currentDate = new Date()) {
    const currentSaison = getSaison(currentDate)
    const birthYear = birth_date.getFullYear()

    const diff = currentSaison - birthYear;
    if (diff < 6) {
        return "SUPER_MINI";
    } else if (diff < 8) {
        return "MINI_POUSSIN";
    } else if (diff < 10) {
        return "POUSSIN";
    } else if (diff < 12) {
        return "BENJAMIN";
    } else if (diff < 14) {
        return "MINIME";
    } else if (diff < 16) {
        return "CADET";
    } else if (diff < 18) {
        return "JUNIOR";
    } else if (diff < 25) {
        return "SENIOR1";
    } else if (diff < 35) {
        return "SENIOR2";
    } else if (diff < 45) {
        return "VETERAN1";
    } else {
        return "VETERAN2";
    }
}

export function getSaison(currentDate = new Date()) {
    if (currentDate.getMonth() >= 8) { //septembre et plus
        return currentDate.getFullYear()
    } else {
        return currentDate.getFullYear() - 1
    }
}
