import WidgetProps from "@insite/client-framework/Types/WidgetProps";
import { pageRenderer } from "@insite/server-framework/PageRenderer";
import { Request, Response } from "express";
import { fetch } from "@insite/client-framework/ServerSideRendering";

const createContentPageRouteHandler = function (
    pageType: string,
    widgetType: string,
    contentType: string,
    contentCallback?: (contentWidget: any, request: Request, response: Response) => string,
) {
    return async (request: Request, response: Response) => {
        const getPageResponse = await fetch(`/api/v2/content/pageByType?type=${pageType}`);

        const json = await getPageResponse.json();

        const { status } = getPageResponse;
        if (status !== 200 || !json.page) {
            response
                .status(status)
                .contentType(getPageResponse.headers.get("Content-Type") ?? "text/plain")
                .send("");
            return;
        }

        if (json.statusCode && json.statusCode !== 200) {
            pageRenderer(request, response);
            return;
        }

        const contentWidget = json.page.widgets.find((x: WidgetProps) => x.type === widgetType);
        let content = contentWidget?.generalFields.contentField;
        if (contentCallback) {
            content = contentCallback(contentWidget, request, response);
        }

        response.header("Cache-Control", "no-cache").contentType(contentType).send(`${content}`);
    };
};

export default createContentPageRouteHandler;
