use anyhow::{Context, Result};

use fyi_core::{Config, DEFAULT_RETENTION, Storage, parse_retention};

pub fn run_gc<S: Storage>(storage: &S, dry_run: bool, retention: Option<String>) -> Result<()> {
    let total = storage.count().context("failed to count events")?;

    // Parse retention period: CLI arg > config > default
    let (retention_str, retention_duration) = if let Some(ref r) = retention {
        let duration = parse_retention(r).unwrap_or(DEFAULT_RETENTION);
        (r.clone(), duration)
    } else {
        // Load config to get retention setting
        let config = Config::load().unwrap_or_default();
        (config.retention.clone(), config.retention_duration())
    };

    if dry_run {
        let expired = storage
            .count_expired(retention_duration)
            .context("failed to count expired events")?;
        println!("Total events: {}", total);
        println!(
            "Retention: {} ({}s)",
            retention_str,
            retention_duration.as_secs()
        );
        println!("Events older than retention: {}", expired);
        println!("Would delete {} event(s)", expired);
    } else {
        let deleted = storage
            .gc(retention_duration)
            .context("failed to run garbage collection")?;
        let remaining = storage.count().context("failed to count events")?;
        println!(
            "Retention: {} ({}s)",
            retention_str,
            retention_duration.as_secs()
        );
        println!("Deleted {} old event(s)", deleted);
        println!("Remaining events: {}", remaining);
    }

    Ok(())
}
