import * as v from "../../../shared/src/valita.js";
import { permissionsConfigSchema, } from "../../../zero-schema/src/compiled-permissions.js";
import { computeZqlSpecs } from "../db/lite-tables.js";
import { elide } from "../types/strings.js";
export function loadPermissions(lc, replica, appID) {
    const { permissions, hash } = replica.get(`SELECT permissions, hash FROM "${appID}.permissions"`);
    if (permissions === null) {
        const appIDFlag = appID === 'zero' ? '' : ` --app-id=${appID}`;
        lc.warn?.(`\n\n\n` +
            `No upstream permissions deployed.\n` +
            `Run 'npx zero-deploy-permissions${appIDFlag}' to enforce permissions.` +
            `\n\n\n`);
        return { permissions, hash: null };
    }
    let obj;
    let parsed;
    try {
        obj = JSON.parse(permissions);
        parsed = v.parse(obj, permissionsConfigSchema);
    }
    catch (e) {
        // TODO: Plumb the --server-version and include in error message.
        throw new Error(`Could not parse upstream permissions: ` +
            `'${elide(String(permissions), 100)}'.\n` +
            `This may happen if Permissions with a new internal format are ` +
            `deployed before the supporting server has been fully rolled out.`, { cause: e });
    }
    return { permissions: parsed, hash };
}
export function reloadPermissionsIfChanged(lc, replica, appID, current) {
    if (current === null) {
        return { permissions: loadPermissions(lc, replica, appID), changed: true };
    }
    const { hash } = replica.get(`SELECT hash FROM "${appID}.permissions"`);
    return hash === current.hash
        ? { permissions: current, changed: false }
        : { permissions: loadPermissions(lc, replica, appID), changed: true };
}
export function getSchema(lc, replica) {
    const specs = computeZqlSpecs(lc, replica);
    const tables = Object.fromEntries([...specs.values()].map(table => {
        const { tableSpec: { name, primaryKey }, zqlSpec: columns, } = table;
        return [name, { name, columns, primaryKey }];
    }));
    return {
        tables,
        relationships: {}, // relationships are already denormalized in ASTs
    };
}
//# sourceMappingURL=load-permissions.js.map