import axios, {type AxiosResponse} from "axios";
import {ResponseError} from "~/classes/responseError";
import {BlacklistItem} from "~/classes/blacklistItem";

const apiUrl = import.meta.env.VITE_API_URL;
const instance = axios.create({
    baseURL: apiUrl
});

const getReportData = (data: AxiosResponse<any, any, {}>): BlacklistItem[] => {
    let result = data.data;
    let blacklistItems: BlacklistItem[] = [];
    for (const [key, value] of Object.entries(result)) {
        let blacklistItem: BlacklistItem = new BlacklistItem(
            value.link,
            value.nicknames,
            value.comments,
            value.afk,
            value.cheater,
            value.griefer,
            value.toxic,
            value.useless,
            value.smurf
        );
        blacklistItems.push(blacklistItem);
    }
    return blacklistItems;
}

export async function getAll(searchText?: string): Promise<BlacklistItem[] | ResponseError | undefined> {
    let result: BlacklistItem[] | ResponseError | undefined;
    let route: string;
    if (searchText !== ''){
        route = '/blacklist/search?text=' + searchText;
    } else {
        route = '/blacklist/all';
    }
    result = await instance.get(route).then((data: AxiosResponse<any, any, {}>) => {
        return getReportData(data);
    }).catch(err => {
        console.log(err);
        return new ResponseError(err.code, err.message, err.status);
    });
    return result;
}