//! §11.6 per-group quotas — global env-var ceilings on a group's shared
//! collections, enforced in the group write path (mirrors the per-value
//! `PICLOUD_*_MAX_*_BYTES` caps). One default applies to every group; per-group
//! configurable limits are deferred.
//!
//! - KV / docs: a per-group ROW-count ceiling (across the group's collections of
//!   that kind). An update of an existing key/doc is net-zero and exempt.
//! - files: a per-group TOTAL-BYTES ceiling (sum of stored blob sizes).

/// Default per-group shared-KV row ceiling. Override `PICLOUD_GROUP_KV_MAX_ROWS`.
pub const DEFAULT_GROUP_KV_MAX_ROWS: u64 = 100_000;
/// Default per-group shared-docs row ceiling. Override `PICLOUD_GROUP_DOCS_MAX_ROWS`.
pub const DEFAULT_GROUP_DOCS_MAX_ROWS: u64 = 100_000;
/// Default per-group shared-files total-bytes ceiling (10 GiB). Override
/// `PICLOUD_GROUP_FILES_MAX_TOTAL_BYTES`.
pub const DEFAULT_GROUP_FILES_MAX_TOTAL_BYTES: u64 = 10 * 1024 * 1024 * 1024;

fn u64_from_env(var: &str, default: u64) -> u64 {
    if let Ok(v) = std::env::var(var) {
        match v.trim().parse::<u64>() {
            Ok(n) if n > 0 => return n,
            _ => tracing::warn!(value = %v, "ignoring invalid {var} (want a positive integer)"),
        }
    }
    default
}

#[must_use]
pub fn group_kv_max_rows_from_env() -> u64 {
    u64_from_env("PICLOUD_GROUP_KV_MAX_ROWS", DEFAULT_GROUP_KV_MAX_ROWS)
}

#[must_use]
pub fn group_docs_max_rows_from_env() -> u64 {
    u64_from_env("PICLOUD_GROUP_DOCS_MAX_ROWS", DEFAULT_GROUP_DOCS_MAX_ROWS)
}

#[must_use]
pub fn group_files_max_total_bytes_from_env() -> u64 {
    u64_from_env(
        "PICLOUD_GROUP_FILES_MAX_TOTAL_BYTES",
        DEFAULT_GROUP_FILES_MAX_TOTAL_BYTES,
    )
}
