import { __awaiter } from "tslib";
import { customAlphabet } from "nanoid";
import React from "react";
import qoreStorageClient from "../hooks/qoreStorageClient";
import getConfig from "next/config";
const { publicRuntimeConfig } = getConfig();
const customVersion = customAlphabet("1234567890QWERTYUIOPASDFGHJKLZXCVBNM", 6);
const useUpdateWhitelist = (projectID, appID) => {
    const { data: app } = qoreStorageClient
        .table("applications")
        .useGetRow(appID, { skip: !appID });
    const { data: env } = qoreStorageClient
        .table("environment")
        .useGetRow(app === null || app === void 0 ? void 0 : app.app_environment, { skip: !appID });
    const { data: releases } = qoreStorageClient.table("release_log").useListRow({
        condition: {
            $and: [
                { status: "success" },
                { release: { project: { id: { $eq: projectID } } } },
                { release: { name: { $eq: !appID ? "staging" : env === null || env === void 0 ? void 0 : env.name } } },
            ],
        },
        orderBy: {
            updated_at: "DESC",
        },
        limit: 1,
    });
    const latestReleaseLog = releases === null || releases === void 0 ? void 0 : releases[0];
    const insertReleaseLog = qoreStorageClient
        .table("release_log")
        .useInsertRow();
    return React.useCallback((address, type = "Hosted") => __awaiter(void 0, void 0, void 0, function* () {
        var _a, _b;
        if (latestReleaseLog) {
            const release = yield insertReleaseLog.insertRow({
                "kube-yaml": "",
                version: customVersion(),
                summary: "",
                status: "deploying",
                release: latestReleaseLog.release,
                config: latestReleaseLog.config,
                stage: latestReleaseLog.stage,
                user_overrides: Object.assign(Object.assign({}, latestReleaseLog.user_overrides), { "qore-data": Object.assign(Object.assign({}, latestReleaseLog.user_overrides["qore-data"]), { allowed_origins: `${latestReleaseLog.user_overrides["qore-data"].allowed_origins},${address}${type === "Hosted" ? publicRuntimeConfig.appsDomain : ""}` }) }),
            });
            return qoreStorageClient.client.project.axios.post("/api/infra/deploy-project", {
                id: (_b = (_a = release === null || release === void 0 ? void 0 : release.results) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b[0].id,
                action: "create_project",
            }, {
                baseURL: "/api/console",
            });
        }
    }), [releases]);
};
export default useUpdateWhitelist;
//# sourceMappingURL=useUpdateWhitelist.js.map