import { __awaiter, __rest } from "tslib";
import { jsx as _jsx } from "@emotion/react/jsx-runtime";
import React from "react";
import { QoreClient } from "@qorebase/client";
import dynamic from "next/dynamic";
import { RuntimeContext } from "@qorebase/app-runtime/src/RuntimeContext";
import { qoreConfig } from "../../../../../../app/hooks/qoreStorageClient";
import { parse } from "cookie";
const PreviewPage = dynamic(() => import("../../../../../../app/preview/PreviewPage"), {
    ssr: false,
});
const RuntimePage = dynamic(() => import("@qorebase/app-runtime/src/RuntimePage"), {
    ssr: false,
});
export const getServerSideProps = (context) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    const { token } = parse(context.req.headers.cookie);
    const appId = context.query.appID;
    const address = context.query.domain;
    const client = new QoreClient({
        endpoint: qoreConfig.endpoint,
        getToken: () => token,
    });
    const domains = yield client
        .view("domain-detail")
        .readRows({
        params: { appId, address },
        populate: ["appdomain"],
    })
        .toPromise();
    console.log("domains", token, appId, address, domains);
    const _b = domains.data.nodes[0] || {}, { appdomain: application } = _b, domain = __rest(_b, ["appdomain"]);
    if (!domain)
        throw new Error("No application is assosiated with this domain");
    if (!application)
        throw new Error("Application not found");
    const revisions = yield client
        .view("revision-list")
        .readRows({
        limit: 1,
        orderBy: { created_at: "DESC" },
        params: {
            appId: application.id,
            projectId: application.project,
        },
    })
        .toPromise();
    const revision = (_a = revisions.data) === null || _a === void 0 ? void 0 : _a.nodes[0];
    if (!revision)
        throw new Error("Revision not found");
    return {
        props: {
            data: {
                application: application,
                revision,
            },
        },
    };
});
export default function Preview({ data, }) {
    const { application, revision } = data;
    const value = React.useMemo(() => application &&
        revision && Object.assign(Object.assign({ name: application.name, description: application.description, theme_color: application.theme_color }, revision.data), { config: Object.assign(Object.assign({}, revision.data.config), { appID: application.id }) }), [revision, application]);
    return (_jsx(RuntimeContext.Provider, { children: _jsx(PreviewPage, Object.assign({ application: data.application }, { children: _jsx(RuntimeContext.Provider, Object.assign({ value: value }, { children: _jsx(RuntimePage, {}) })) })) }));
}
//# sourceMappingURL=%5Bdomain%5D.js.map