import { useAuthenticateManagedIdentityWithInstantAccess, useLocale, } from "@saasquatch/component-boilerplate";
import { useState } from "@saasquatch/universal-hooks";
import jsonpointer from "jsonpointer";
import { useRegistrationFormState } from "../sqm-portal-registration-form/useRegistrationFormState";
export function useInstantAccessRegistration(props) {
  const locale = useLocale();
  const cookie = new URLSearchParams(window.location.search);
  const cookies = cookie === null || cookie === void 0 ? void 0 : cookie.get("_saasquatch");
  const { registrationFormState, setRegistrationFormState } = useRegistrationFormState();
  const [request, { loading, errors, data }] = useAuthenticateManagedIdentityWithInstantAccess();
  const [error, setError] = useState("");
  const submit = async (event) => {
    var _a;
    setError("");
    let formControls = event.target.getFormControls();
    let formData = event.detail.formData;
    let validationErrors = {};
    formControls === null || formControls === void 0 ? void 0 : formControls.map((control) => {
      if (!control.name)
        return;
      const key = control.name;
      const value = control.value;
      jsonpointer.set(formData, key, value);
      if (control.required && !value) {
        jsonpointer.set(validationErrors, key, props.requiredFieldErrorMessage);
      }
      // custom validation
      if (typeof control.validationError === "function") {
        const validate = control.validationError;
        const validationError = validate({ control, key, value });
        if (validationError)
          jsonpointer.set(validationErrors, key, validationError);
      }
    });
    const variables = {
      firstName: formData.firstName,
      lastName: formData.lastName,
      email: formData.email,
      locale,
      ...((props === null || props === void 0 ? void 0 : props.includeCookies) && cookies ? { cookies } : {}),
    };
    try {
      const result = await request(variables);
      if (result instanceof Error) {
        throw result;
      }
      setRegistrationFormState({
        ...registrationFormState,
        loading: false,
        error: "",
        validationErrors: {},
      });
    }
    catch (error) {
      // check for invalid email
      if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes("is not valid")) {
        setRegistrationFormState({
          ...registrationFormState,
          loading: false,
          error: "",
          validationErrors: { email: props.invalidEmailErrorMessage },
        });
      }
      else if ((error === null || error === void 0 ? void 0 : error.name) === "fraud_error") {
        setRegistrationFormState({
          ...registrationFormState,
          loading: false,
          error: "FRAUD",
        });
      }
      else {
        setRegistrationFormState({
          ...registrationFormState,
          loading: false,
          error: props.networkErrorMessage,
          validationErrors: {},
        });
      }
    }
  };
  return {
    states: {
      loading,
      error: registrationFormState === null || registrationFormState === void 0 ? void 0 : registrationFormState.error,
      registrationFormState,
    },
    callbacks: {
      submit,
    },
  };
}
