import { Tariff, makeRequest } from "@frontend/kitui";
import { parseAxiosError } from "@root/utils/parse-error";

import type { PrivilegeWithoutPrice, ServiceKeyToPrivilegesMap } from "@root/model/privilege";
import type { GetTariffsResponse } from "@root/model/tariff";
import { removeTariffFromCart } from "@root/stores/user";

const apiUrl = process.env.REACT_APP_DOMAIN + "/strator"
console.log("домен с которого тарифы запрашиваются", process.env.REACT_APP_DOMAIN)
console.log("домен с которого тарифы запрашиваются", apiUrl)

export async function getTariffs(
    apiPage: number,
    tariffsPerPage: number,
    signal: AbortSignal | undefined
): Promise<[GetTariffsResponse | null, string?]> {
    try {
        const tariffsResponse = await makeRequest<never, GetTariffsResponse>({
            url: apiUrl + `/tariff?page=${apiPage}&limit=${tariffsPerPage}`,
            method: "get",
            useToken: true,
            signal,
        });

        return [tariffsResponse];
    } catch (nativeError) {
        const [error] = parseAxiosError(nativeError);

        return [null, `Не удалось получить список тарифов. ${error}`];
    }
}

interface CreateTariffBody {
    name: string;
    price?: number;
    isCustom: boolean;
    privileges: PrivilegeWithoutPrice[];
}

export async function createTariff(tariff: CreateTariffBody): Promise<[Tariff | null, string?]> {
    try {
        const createTariffResponse = await makeRequest<CreateTariffBody, Tariff>({
            url: `${apiUrl}/tariff`,
            method: "post",
            useToken: true,
            body: tariff,
        });

        return [createTariffResponse];
    } catch (nativeError) {
        const [error] = parseAxiosError(nativeError);

        return [null, `Не удалось создать тариф. ${error}`];
    }
}

export async function getTariffById(tariffId: string): Promise<[Tariff | null, string?, number?]> {
    try {
        const getTariffByIdResponse = await makeRequest<never, Tariff>({
            url: `${apiUrl}/tariff/${tariffId}`,
            method: "get",
            useToken: true,
        });

        return [getTariffByIdResponse];
    } catch (nativeError) {
        const [error, status] = parseAxiosError(nativeError);

        return [null, `Не удалось получить тарифы. ${error}`, status];
    }
}

export async function getCustomTariffs(
    signal: AbortSignal | undefined
): Promise<[ServiceKeyToPrivilegesMap | null, string?]> {
    try {
        const customTariffsResponse = await makeRequest<null, ServiceKeyToPrivilegesMap>({
            url: apiUrl + "/privilege/service",
            signal,
            method: "get",
            useToken: true,
        });

        const tempCustomTariffsResponse = {
            ...customTariffsResponse,
            squiz: customTariffsResponse.squiz
        };

        return [tempCustomTariffsResponse];
    } catch (nativeError) {
        const [error] = parseAxiosError(nativeError);

        return [null, `Не удалось получить мои тарифы. ${error}`];
    }
}

export async function getTariffArray(tariffIds: string[] | undefined) {
    if (!tariffIds) return null;

    const responses = await Promise.allSettled(tariffIds.map(tariffId =>
        makeRequest<never, Tariff>({
            url: `${apiUrl}/tariff/${tariffId}`,
            method: "get",
            useToken: true,
        })
    ));

    const tariffs: Tariff[] = [];

    responses.forEach((response, index) => {
        switch (response.status) {
            case "fulfilled": {
                tariffs.push(response.value);
                break;
            }
            case "rejected": {
                const [, status] = parseAxiosError(response.reason);
                if (status === 404) removeTariffFromCart(tariffIds[index]);
                break;
            }
        }
    });

    return tariffs;
}
