import { state as checkoutState } from '@store/checkout';
import { state as processorsState } from '@store/processors';
import { addQueryArgs, getQueryArg } from '@wordpress/url';
import apiFetch from '../../functions/fetch';
/** The base url for this service. */
export const baseUrl = 'surecart/v1/checkouts/';
/** Items to always expand. */
export const expand = [
  'line_items',
  'line_item.price',
  'line_item.fees',
  'price.product',
  'customer',
  'customer.shipping_address',
  'payment_intent',
  'discount',
  'discount.promotion',
  'recommended_bumps',
  'bump.price',
  'discount.coupon',
  'shipping_address',
  'staged_payment_intents',
  'tax_identifier',
  'manual_payment_method',
];
/** Default data we send with every request. */
export const withDefaultData = (data = {}) => {
  var _a, _b, _c, _d;
  return ({
    live_mode: checkoutState.mode !== 'test',
    group_key: checkoutState.groupId,
    abandoned_checkout_return_url: checkoutState.abandonedCheckoutReturnUrl || null,
    abandoned_checkout_enabled: checkoutState.abandonedCheckoutEnabled && !!checkoutState.abandonedCheckoutReturnUrl,
    metadata: {
      ...((data === null || data === void 0 ? void 0 : data.metadata) || {}),
      ...(((_a = window === null || window === void 0 ? void 0 : window.scData) === null || _a === void 0 ? void 0 : _a.page_id) && { page_id: (_b = window === null || window === void 0 ? void 0 : window.scData) === null || _b === void 0 ? void 0 : _b.page_id }),
      ...(((_c = checkoutState === null || checkoutState === void 0 ? void 0 : checkoutState.product) === null || _c === void 0 ? void 0 : _c.id) && { buy_page_product_id: (_d = checkoutState === null || checkoutState === void 0 ? void 0 : checkoutState.product) === null || _d === void 0 ? void 0 : _d.id }),
      page_url: window.location.href,
    },
    ...data,
  });
};
/** Default query we send with every request. */
export const withDefaultQuery = (query = {}) => {
  var _a, _b;
  return ({
    ...(!!(checkoutState === null || checkoutState === void 0 ? void 0 : checkoutState.formId) && { form_id: checkoutState === null || checkoutState === void 0 ? void 0 : checkoutState.formId }),
    ...(!!((_a = checkoutState === null || checkoutState === void 0 ? void 0 : checkoutState.product) === null || _a === void 0 ? void 0 : _a.id) && { product_id: (_b = checkoutState === null || checkoutState === void 0 ? void 0 : checkoutState.product) === null || _b === void 0 ? void 0 : _b.id }),
    ...(!!processorsState.config.stripe.paymentElement && { stage_processor_type: 'stripe' }),
    ...query,
  });
};
/** Get the checkout id  */
export const findInitialCheckoutId = () => {
  var _a, _b;
  // check url first.
  const checkoutId = getQueryArg(window.location.href, 'checkout_id');
  if (!!checkoutId) {
    return checkoutId;
  }
  // check existing order.
  if ((_a = checkoutState === null || checkoutState === void 0 ? void 0 : checkoutState.checkout) === null || _a === void 0 ? void 0 : _a.id) {
    return (_b = checkoutState === null || checkoutState === void 0 ? void 0 : checkoutState.checkout) === null || _b === void 0 ? void 0 : _b.id;
  }
  // we don't have and order id.
  return null;
};
/** Parse the path with expansions. */
export const parsePath = (id, endpoint = '') => {
  let path = id ? `${baseUrl}${id}` : baseUrl;
  path = `${path}${endpoint}`;
  return addQueryArgs(path, {
    expand,
  });
};
/** Fethc a checkout by id */
export const fetchCheckout = async ({ id, query = {} }) => {
  return (await apiFetch({
    path: addQueryArgs(parsePath(id), withDefaultQuery(query)),
  }));
};
/** Create or update the checkout. */
export const createOrUpdateCheckout = async ({ id = null, data = {}, query = {} }) => {
  id = !id ? findInitialCheckoutId() : id;
  return await apiFetch({
    method: id ? 'PATCH' : 'POST',
    path: addQueryArgs(parsePath(id), withDefaultQuery(query)),
    data: withDefaultData(data),
  });
};
/** Update the checkout. */
export const updateCheckout = async ({ id, data = {}, query = {} }) => {
  return await apiFetch({
    method: 'PATCH',
    path: addQueryArgs(parsePath(id), withDefaultQuery(query)),
    data: withDefaultData(data),
  });
};
/** Finalize a checkout */
export const finalizeCheckout = async ({ id, data = {}, query = {}, processor }) => {
  return (await apiFetch({
    method: 'POST',
    path: addQueryArgs(parsePath(id, '/finalize'), withDefaultQuery({
      ...((processor === null || processor === void 0 ? void 0 : processor.manual) ? { manual_payment: true, manual_payment_method_id: processor === null || processor === void 0 ? void 0 : processor.id } : { processor_type: processor === null || processor === void 0 ? void 0 : processor.id }),
      ...query,
    })),
    data: withDefaultData(data),
  }));
};
