import { createEvent, OdpEvent, sendEvent } from "@insite/client-framework/OdpEvents/OdpEvent";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import PageProps from "@insite/client-framework/Types/PageProps";

export const sendPageViewEvent = (
    page: PageProps,
    state: ApplicationState,
    customize?: (odpEvent: OdpEvent) => void,
) => {
    if (!state.context) {
        // when in the CMS shell the initial page load happens in a way that this is undefined so just bail
        return;
    }
    const currentPageId = page.nodeId;
    const isHomePage = page.type === "HomePage";

    const odpEvent = createEvent("pageview", state);
    // we call this event before updating the redux store so need to pass in the actual current page.
    odpEvent.basics.page_id = currentPageId;

    if (isHomePage) {
        odpEvent.properties["action"] = "website";
    }

    customize?.(odpEvent);

    sendEvent(odpEvent, state);
};
