import { __awaiter, __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
import React from "react";
import { QoreClient } from "@qorebase/client";
import { RuntimeContext } from "@qorebase/app-runtime/src/RuntimeContext";
import dynamic from "next/dynamic";
import { Image, Text, Box } from "@chakra-ui/react";
import { css, Global } from "@emotion/react";
import absoluteUrl from "next-absolute-url";
import { qoreConfig } from "../app/hooks/qoreStorageClient";
import RuntimeHead from "@qorebase/app-runtime/src/RuntimeHead";
import Head from "next/head";
const ClientRuntime = dynamic(() => import("@qorebase/app-runtime/src/ClientRuntime"), {
    ssr: false,
});
const reservedAddress = ["page", "favicon.ico"];
export const getServerSideProps = (context) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b, _c, _d, _e;
    const { host } = absoluteUrl(context.req);
    const isSubdomain = host.endsWith(process.env.NEXT_PUBLIC_APPS_DOMAIN) ||
        !((_a = context.query.domain) === null || _a === void 0 ? void 0 : _a[0]) ||
        reservedAddress.includes((_b = context.query.domain) === null || _b === void 0 ? void 0 : _b[0]);
    const address = isSubdomain
        ? host.replace(process.env.NEXT_PUBLIC_APPS_DOMAIN, "")
        : (_c = context.query.domain) === null || _c === void 0 ? void 0 : _c[0];
    const client = new QoreClient(qoreConfig);
    client.project.axios.defaults.headers["x-qore-engine-admin-secret"] =
        qoreConfig.adminSecret;
    const domains = yield client
        .table("domains")
        .readRows({
        condition: {
            $and: [{ address: { $eq: address } }],
        },
        populate: ["appdomain"],
    })
        .toPromise();
    const _f = (((_d = domains.data) === null || _d === void 0 ? void 0 : _d.nodes[0]) ||
        {}), { appdomain: application } = _f, domain = __rest(_f, ["appdomain"]);
    if (!domain) {
        return {
            props: {
                data: {},
                error: {
                    type: "NO_DOMAIN",
                    message: "No application is assosiated with this domain",
                },
            },
        };
    }
    if (!application) {
        return {
            props: {
                data: {},
                error: {
                    type: "NO_APPLICATION",
                    message: "Application not found!",
                },
            },
        };
    }
    const revisionResult = yield client
        .table("revisions")
        .readRows({
        condition: {
            apprevision: application.id,
        },
        orderBy: { created_at: "DESC" },
        limit: 1,
    })
        .toPromise();
    const revision = (_e = revisionResult.data) === null || _e === void 0 ? void 0 : _e.nodes[0];
    if (!revision) {
        return {
            props: {
                data: {},
                error: {
                    type: "NO_REVISION",
                    message: "Application schema not found!",
                },
            },
        };
    }
    return {
        props: {
            data: {
                application: application,
                revision,
                basename: isSubdomain ? "/" : `/${address}`,
            },
        },
    };
});
export default function ApplicationPage({ data, error, }) {
    const { application, revision } = data;
    const schema = 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]);
    if (error) {
        return (_jsxs(Box, Object.assign({ h: "100vh", w: "100vw", display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center" }, { children: [_jsx(Image, { boxSize: "sm", src: "/assets/no-app.svg", alt: "no application", marginBottom: "-56px" }), _jsx(Text, Object.assign({ fontSize: "xl" }, { children: "No application found!" }))] })));
    }
    return (_jsxs(RuntimeContext.Provider, Object.assign({ value: schema }, { children: [_jsx(Global, { styles: css `
          #__next {
            min-height: 100vh;
            /* mobile viewport bug fix */
            min-height: -webkit-fill-available;
          }

          html {
            height: -webkit-fill-available;
          }
        ` }), _jsx(Head, { children: _jsx(RuntimeHead, { schema: schema }) }), _jsx(ClientRuntime, { basename: data.basename, schema: schema })] })));
}
//# sourceMappingURL=index.js.map