import { env } from "../../env.js";

//#region src/auth/authz/config.ts
/**
* Check if a SpiceDB endpoint is localhost (used for TLS auto-detection).
*/
function isLocalhostEndpoint(endpoint) {
	return endpoint.startsWith("localhost") || endpoint.startsWith("127.0.0.1");
}
/**
* Get SpiceDB connection configuration from environment variables.
* TLS is auto-detected: disabled for localhost, enabled for remote endpoints.
*/
function getSpiceDbConfig() {
	const endpoint = env.SPICEDB_ENDPOINT || "localhost:50051";
	return {
		endpoint,
		token: env.SPICEDB_PRESHARED_KEY || "",
		tlsEnabled: env.SPICEDB_TLS_ENABLED ?? !isLocalhostEndpoint(endpoint)
	};
}
const SPICEDB_ID_SEPARATOR = "/";
/**
* Compose a tenant-scoped SpiceDB project object ID.
*
* Format: `{tenantId}/{projectId}` — projects' backing-store PK is
* `(tenantId, projectId)`, so this mirrors that composite key verbatim.
*/
function toSpiceDbProjectId(tenantId, projectId) {
	return `${tenantId}${SPICEDB_ID_SEPARATOR}${projectId}`;
}
/**
* Parse a tenant-scoped SpiceDB project object ID back into its parts.
*
* @returns `{ tenantId, projectId }` extracted from the composite ID.
* @throws if the ID does not contain the separator.
*/
function fromSpiceDbProjectId(spiceDbProjectId) {
	const separatorIndex = spiceDbProjectId.indexOf(SPICEDB_ID_SEPARATOR);
	if (separatorIndex === -1) throw new Error(`Invalid SpiceDB project ID format: ${spiceDbProjectId}`);
	return {
		tenantId: spiceDbProjectId.substring(0, separatorIndex),
		projectId: spiceDbProjectId.substring(separatorIndex + 1)
	};
}
/**
* Compose a tenant+project-scoped SpiceDB credential_reference object ID.
*
* Format: `{tenantId}/{projectId}/{credentialReferenceId}` — credentials' backing-store
* PK is `(tenantId, projectId, id)`, so this mirrors that composite key verbatim.
* Without this scoping, two tenants that each define a credential with the same
* slug (e.g. `cred_helpscout`) would share the same SpiceDB object and any grant
* on one would appear to grant the other.
*/
function toSpiceDbCredentialReferenceId(tenantId, projectId, credentialReferenceId) {
	return `${tenantId}${SPICEDB_ID_SEPARATOR}${projectId}${SPICEDB_ID_SEPARATOR}${credentialReferenceId}`;
}

//#endregion
export { fromSpiceDbProjectId, getSpiceDbConfig, isLocalhostEndpoint, toSpiceDbCredentialReferenceId, toSpiceDbProjectId };