import { makeRequest } from "@frontend/kitui";
import { SendPaymentRequest, SendPaymentResponse } from "@root/model/wallet";
import { parseAxiosError } from "@root/utils/parse-error";

const isStaging = (() => {
  const host = window.location.hostname;
  return host.includes("s") ? "s" : "";
})();

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

interface PaymentBody {
  type: string;
  amount: number;
}

export async function sendPayment({
  userId,
  body,
  fromSquiz,
  paymentPurpose,
}: {
  userId: string;
  body: PaymentBody;
  fromSquiz: boolean;
  paymentPurpose: "paycart" | "replenishwallet";
}): Promise<[SendPaymentResponse | null, string?]> {
  try {
    const sendPaymentResponse = await makeRequest<
      SendPaymentRequest,
      SendPaymentResponse
    >({
      url: apiUrl + "/wallet",
      contentType: true,
      method: "POST",
      useToken: true,
      withCredentials: false,
      body: {
        currency: "RUB",
        bankCard: {
          number: "RUB",
          expiryYear: "2021",
          expiryMonth: "05",
          csc: "05",
          cardholder: "IVAN IVANOV",
        },
        phoneNumber: "79000000000",
        login: "login_test",
        returnUrl: `https://${isStaging}hub.pena.digital/afterpay?from=${
          fromSquiz ? "quiz" : "hub"
        }&purpose=${paymentPurpose}&userid=${userId}`,
        ...body,
      },
    });

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

    return [null, `Ошибка оплаты. ${error}`];
  }
}

export const sendRSPayment = async (money: number): Promise<string | null> => {
  try {
    await makeRequest<unknown, string>({
      url: apiUrl + "/wallet/rspay",
      method: "POST",
      useToken: true,
      body: { money: money },
      withCredentials: false,
    });

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

    return `Ошибка оплаты. ${error}`;
  }
};
