import { UserAccount, makeRequest } from "@frontend/kitui"
import  { AxiosError } from "axios"

import { parseAxiosError } from "@root/utils/parse-error"

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

export async function patchCart(
	tariffId: string
): Promise<[string[], string?]> {
	try {
		const patchCartResponse = await makeRequest<never, UserAccount>({
			url: apiUrl + `/cart?id=${tariffId}`,
			method: "PATCH",
			useToken: true,
		})

		return [patchCartResponse.cart]
	} catch (nativeError) {
		let [error, status] = parseAxiosError(nativeError)
		if (status === 400 && error.indexOf("invalid id") !== -1) error = "Данный тариф более недоступен"

		return [[], `Не удалось добавить товар в корзину. ${error}`]
	}
}

export async function deleteCart(
	tariffId: string
): Promise<[string[], string?]> {
	try {
		const deleteCartResponse = await makeRequest<never, UserAccount>({
			url: apiUrl + `/cart?id=${tariffId}`,
			method: "DELETE",
			useToken: true,
		})

		return [deleteCartResponse.cart]
	} catch (nativeError) {
		const [error] = parseAxiosError(nativeError)

		return [[], `Не удалось удалить товар из корзины. ${error}`]
	}
}

export async function payCart(): Promise<[UserAccount | null, string?]> {
	try {
		const payCartResponse = await makeRequest<never, UserAccount>({
			url: apiUrl + "/cart/pay",
			method: "POST",
			useToken: true,
		})

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

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

export async function patchCurrency(
	currency: string
): Promise<[UserAccount | null, string?]> {
	try {
		const patchCurrencyResponse = await makeRequest<
      { currency: string },
      UserAccount
    >({
    	url: apiUrl + "/wallet",
    	method: "PATCH",
    	useToken: true,
    	body: {
    		currency,
    	},
    })

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

		return [null, `Не удалось изменить валюту. ${error}`]
	}
}