import { parse } from "../../../shared/src/valita.js";
import { elide } from "../types/strings.js";
import { permissionsConfigSchema } from "../../../zero-schema/src/compiled-permissions.js";
import { computeZqlSpecs } from "../db/lite-tables.js";
//#region ../zero-cache/src/auth/load-permissions.ts
function loadPermissions(lc, replica, appID, config) {
	const { permissions, hash } = replica.get(`SELECT permissions, hash FROM "${appID}.permissions"`);
	if (permissions === null) {
		if (!(config !== void 0 && (config.push?.url !== void 0 || config.mutate?.url !== void 0) && (config.query?.url !== void 0 || config.getQueries?.url !== void 0))) {
			const appIDFlag = appID === "zero" ? "" : ` --app-id=${appID}`;
			lc.warn?.(`


No upstream permissions deployed.
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 = parse(obj, permissionsConfigSchema);
	} catch (e) {
		throw new Error(`Could not parse upstream permissions: '${elide(String(permissions), 100)}'.\nThis 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
	};
}
function reloadPermissionsIfChanged(lc, replica, appID, current, config) {
	if (current === null) return {
		permissions: loadPermissions(lc, replica, appID, config),
		changed: true
	};
	const { hash } = replica.get(`SELECT hash FROM "${appID}.permissions"`);
	return hash === current.hash ? {
		permissions: current,
		changed: false
	} : {
		permissions: loadPermissions(lc, replica, appID, config),
		changed: true
	};
}
function getSchema(lc, replica) {
	const specs = computeZqlSpecs(lc, replica, { includeBackfillingColumns: false });
	return {
		tables: Object.fromEntries(Array.from(specs.values(), (table) => {
			const { tableSpec: { name, primaryKey }, zqlSpec: columns } = table;
			return [name, {
				name,
				columns,
				primaryKey
			}];
		})),
		relationships: {}
	};
}
//#endregion
export { getSchema, loadPermissions, reloadPermissionsIfChanged };

//# sourceMappingURL=load-permissions.js.map