#!/usr/bin/env bash
# gniza4cp/lib/retention.sh — Delete old snapshots beyond RETENTION_COUNT on remote

enforce_retention() {
    local user="$1"
    local keep="${RETENTION_COUNT:-$DEFAULT_RETENTION_COUNT}"

    log_debug "Enforcing retention for $user: keeping $keep snapshots"

    # Get completed snapshots sorted newest first
    local snapshots; snapshots=$(list_remote_snapshots "$user")
    if [[ -z "$snapshots" ]]; then
        log_debug "No snapshots found for $user, nothing to prune"
        return 0
    fi

    local count=0
    local pruned=0
    while IFS= read -r snap; do
        ((count++)) || true
        if (( count > keep )); then
            log_info "Pruning old snapshot for $user: $snap"
            if _is_rclone_mode; then
                rclone_purge "accounts/${user}/snapshots/${snap}" || {
                    log_warn "Failed to purge snapshot: $snap"
                }
            else
                local snap_dir; snap_dir=$(get_snapshot_dir "$user")
                remote_exec "rm -rf '$snap_dir/$snap'" || {
                    log_warn "Failed to prune snapshot: $snap_dir/$snap"
                }
            fi
            ((pruned++)) || true
        fi
    done <<< "$snapshots"

    if (( pruned > 0 )); then
        log_info "Pruned $pruned old snapshot(s) for $user"
    fi
}
