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

import type { ServiceKeyToPrivilegesMap } from "@root/model/privilege"
import type { GetTariffsResponse } from "@root/model/tariff"

const apiUrl = process.env.REACT_APP_DOMAIN + "/strator"

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}`]
	}
}

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 getCustomTariffsResponse = await makeRequest<null, ServiceKeyToPrivilegesMap>({
			url: apiUrl + "/privilege/service",
			signal,
			method: "get",
			useToken: true,
		})

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

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