import { AdminOptions, UserProfileViewModel } from "@insite/shell/Services/AdminService";
import userflow from "userflow.js";

let wasInitialized = false;
let storedOptions: AdminOptions;
let storedCurrentUser: UserProfileViewModel | null;

let originalPushState = window.history.pushState;

const identify = () => {
    if (!storedOptions || !storedCurrentUser) {
        return;
    }

    // this is used as a display value in userflow UI so populate it with userName if the other two are blank
    let name = storedCurrentUser.userName;
    if (storedCurrentUser.firstName && storedCurrentUser.lastName) {
        name = `${storedCurrentUser.firstName} ${storedCurrentUser.lastName}`;
    } else if (storedCurrentUser.firstName) {
        name = storedCurrentUser.firstName;
    } else if (storedCurrentUser.lastName) {
        name = storedCurrentUser.lastName;
    }

    userflow.identify(storedCurrentUser.userName, {
        name,
        email: storedCurrentUser.email,
        masterCustomerId: storedOptions.turnstile.masterCustomerId,
        organizationId: storedOptions.turnstile.organizationId,
        organizationName: storedOptions.turnstile.organizationName,
        commerceVersion: storedOptions.environment.commerceVersion,
        productId: storedOptions.turnstile.productId,
        commerceFeatures: storedOptions.userflow.features,
    });
};

window.history.pushState = function (...args) {
    originalPushState.apply(this, args);

    identify();
};

export const initializeUserflow = (options: AdminOptions, currentUser: UserProfileViewModel | null) => {
    storedOptions = options;
    storedCurrentUser = currentUser;
    if (!options.userflow.token || wasInitialized) {
        return;
    }

    wasInitialized = true;

    userflow.init(options.userflow.token);
    identify();
};
