export default function useRedDot() {
  const config = useRuntimeConfig().public;
  class MDirectPayment implements TDirectPayment {
    _id?: string; // Used for Reference only temporary
    mid: string;
    api_mode: string;
    payment_type: string;
    order_id: string; // unitBi
    ccy: string;
    amount: number;
    card_no?: string;
    exp_date?: string | Date;
    cvv2?: string | number;
    payer_name?: string;
    payer_email?: string;
    merchant_reference?: string;
    back_url?: string; // for redirect payment
    redirect_url?: string; // for redirect payment
    notify_url?: string; // for redirect payment
    bill_to_address_city?: string;
    bill_to_address_line1?: string;
    bill_to_address_country?: string;
    bill_to_address_postal_code?: string;
    signature?: string;
    constructor(data: Partial<TDirectPayment> = {}) {
      this._id = data._id || "";
      this.mid = data.mid || "";
      this.api_mode = data.api_mode || "";
      this.payment_type = data.payment_type || "";
      this.order_id = data.order_id || "";
      this.ccy = data.ccy || "";
      this.amount = data.amount || 0;
      this.card_no = data.card_no || "";
      this.exp_date = data.exp_date || new Date();
      this.cvv2 = data.cvv2 || "";
      this.payer_name = data.payer_name || "";
      this.payer_email = data.payer_email || "";
      this.merchant_reference = data.merchant_reference || "";
      this.back_url = data.back_url || "";
      this.redirect_url = data.redirect_url || "";
      this.notify_url = data.notify_url || "";
      this.bill_to_address_city = data.bill_to_address_city || "";
      this.bill_to_address_line1 = data.bill_to_address_line1 || "";
      this.bill_to_address_country = data.bill_to_address_country || "";
      this.bill_to_address_postal_code = data.bill_to_address_postal_code || "";
      this.signature = data.signature || "";
    }
  }

  const apiEndpoint = "/api/payment/v1";
  const reddotApiEndpoint = "/api/reddot/v1";
  const item = useState("red-dot", () => new MDirectPayment());
  const filter = useState("billing-ticketSearch", () => "");
  const filterOptions = useState("unit-billFilterOptions", () => []);
  const isLoading = useState("unit-billIsLoading", () => false);
  const isAdding = useState("unit-billIsAdding", () => false);
  const isUpdating = useState("unit-billIsUpdating", () => false);
  const isDeleting = useState("unit-billIsDeleting", () => false);
  const isValid = useState("unit-billIsValid", () => false);
  /**
   * CRUD OPERATIONS FROM BE:
   * **/

  // GET PAYMENT URL
  async function getPaymentUrl(payload: TDirectPayment) {
    // ------------------ FOR REDDOT REDIRECT API ---------------------------- //
    const baseURL = config?.APP_MAIN || "";

    const BACK_URL = payload?.backURL
      ? `${baseURL}${payload?.backURL}&refId=${payload?.order_id || ""}`
      : `${baseURL}/billing?cancel=true&refId=${payload?.order_id || ""}`;
    const REDIRECT_URL = payload?.successURL
      ? `${baseURL}${payload?.successURL}`
      : `${baseURL}/billing/payment-success`;
    const NOTIFY_URL = `${baseURL}/billing/payment-success`;
    isLoading.value = true;

    const response = useNuxtApp().$api(`${reddotApiEndpoint}`, {
      method: "POST",
      body: {
        mid: payload.mid,
        merchant_key: payload.merchant_key,
        order_id: payload.order_id, // reference number
        amount: payload.amount,
        back_url: BACK_URL,
        redirect_url: REDIRECT_URL,
        notify_url: NOTIFY_URL,
      },
    });
    isLoading.value = false;
    return response;
  }

  async function getPaymentUrlFacility(payload: TDirectPayment) {
    // ------------------ FOR REDDOT REDIRECT API ---------------------------- //
    const baseURL = config?.APP_MAIN || "";
    // const BACK_URL = "http://localhost:4011/billing";
    // const REDIRECT_URL = "http://localhost:4011/billing/payment-success";
    // const NOTIFY_URL = "http://localhost:4011/billing/payment-success";
    const BACK_URL = payload?.backURL ? `${baseURL}${payload?.backURL}` : ``;
    const REDIRECT_URL = payload?.successURL
      ? `${baseURL}${payload?.successURL}`
      : `${baseURL}/billing/payment-success`;
    const NOTIFY_URL = `${baseURL}/billing/payment-success`;

    isLoading.value = true;

    const response = useNuxtApp().$api(`${reddotApiEndpoint}`, {
      method: "POST",
      body: {
        mid: payload.mid,
        mkey: payload.merchant_key,
        order_id: payload.order_id, // reference number
        amount: payload.amount,
        back_url: BACK_URL,
        redirect_url: REDIRECT_URL,
        notify_url: NOTIFY_URL,
      },
    });
    isLoading.value = false;
    return response;
  }

  // ENQUIRE TRANSACTION
  async function enquirePaymentTransaction(payload: TDirectPayment) {
    isLoading.value = true;
    const response = useNuxtApp().$api(`${reddotApiEndpoint}/enquiry`, {
      method: "POST",
      body: {
        request_mid: payload.request_mid,
        transaction_id: payload.transaction_id, // reference number
        merchant_key: payload.merchant_key,
        method: payload.method,
      },
    });

    isLoading.value = false;
    return response;
  }

  // GET MERCHANT DETAILS BY ID
  async function getMerchantDetailsById(id: string) {
    isLoading.value = true;
    const response = useNuxtApp().$api(`${reddotApiEndpoint}/merchant/${id}`);

    isLoading.value = false;
    return response;
  }

  // GET CART BY REFERENCE NUMBER
  async function getCartById(referenceNumber: string) {
    const params = new URLSearchParams();

    if (referenceNumber) params.set("refId", String(referenceNumber));
    return useNuxtApp().$api(`${apiEndpoint}/get-cart?${params.toString()}`);
  }

  // CANCEL CHECKED OUT CART
  async function cancelCart(referenceNumber: string) {
    const params = new URLSearchParams();

    if (referenceNumber) params.set("refId", String(referenceNumber));
    return useNuxtApp().$api(
      `${apiEndpoint}/cancel-cart?${params.toString()}`,
      {
        method: "DELETE",
      }
    );
  }

  function createRDPAccount(payload: TReddotCreateAccount) {
    return useNuxtApp().$api("/api/payment-gateways/v1", {
      method: "POST",
      body: payload,
    });
  }

  function getBySiteTypeMethod(
    site: string,
    paymentType: string,
    paymentMethod: string,
    userType: string
  ) {
    const payload = { site, paymentType, paymentMethod, userType };
    return useNuxtApp().$api("/api/payment-gateways/get/v1", {
      method: "POST",
      body: payload,
    });
  }

  return {
    item,
    isValid,
    isLoading,
    isAdding,
    isUpdating,
    isDeleting,
    filter,
    filterOptions,
    getPaymentUrl,
    getPaymentUrlFacility,
    enquirePaymentTransaction,
    getMerchantDetailsById,
    getCartById,
    cancelCart,
    createRDPAccount,
    getBySiteTypeMethod,
  };
}
