import { getUrl } from "@insite/client-framework/ServerSideRendering";
import { LinkProps } from "@insite/mobius/Link";

const prepareBreadcrumbStructuredPageData = (breadcrumbLinks?: LinkProps[]) => {
    if (!breadcrumbLinks) {
        return "";
    }

    const url: { protocol: string; host: string } = IS_SERVER_SIDE ? getUrl()! : window.location;
    const authority = `${url.protocol}//${url.host}`;

    const data = {
        "@context": "https://schema.org",
        "@type": "BreadcrumbList",
        itemListElement: breadcrumbLinks.map((o, index) => ({
            "@type": "ListItem",
            position: index + 1,
            name: o.children,
            item: authority + o.href,
        })),
    } as any;

    if (breadcrumbLinks.length) {
        delete data["itemListElement"][breadcrumbLinks.length - 1]["item"];
    }

    return JSON.stringify(data);
};

export default prepareBreadcrumbStructuredPageData;
