use std::path::Path;

use crate::plugin::{CleanAction, CleanTarget, Plugin, Safety};
use crate::utils;

pub struct PnpmPlugin;

impl Plugin for PnpmPlugin {
    fn name(&self) -> &str {
        "pnpm"
    }

    fn description(&self) -> &str {
        "pnpm content-addressable store and metadata cache"
    }

    fn scan_directory(&self, _dir: &Path) -> Vec<CleanTarget> {
        Vec::new()
    }

    fn global_targets(&self) -> Vec<CleanTarget> {
        let mut targets = Vec::new();

        let cache_dir = pnpm_cache_dir();
        if cache_dir.is_dir() {
            let size = utils::dir_size(&cache_dir);
            targets.push(CleanTarget {
                label: format!("{}", cache_dir.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(cache_dir),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "pnpm package cache, re-downloaded as needed".to_string(),
            });
        }

        // pnpm global store
        let store_dir = pnpm_store_dir();
        if store_dir.is_dir() {
            let size = utils::dir_size(&store_dir);
            targets.push(CleanTarget {
                label: format!("{}", store_dir.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(store_dir),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "pnpm content-addressable store, re-downloaded as needed".to_string(),
            });
        }

        targets
    }

    fn is_available(&self) -> bool {
        pnpm_cache_dir().is_dir() || pnpm_store_dir().is_dir()
    }
}

fn pnpm_cache_dir() -> std::path::PathBuf {
    if cfg!(target_os = "macos") {
        utils::home_dir().join("Library/Caches/pnpm")
    } else {
        utils::home_dir().join(".cache/pnpm")
    }
}

fn pnpm_store_dir() -> std::path::PathBuf {
    if cfg!(target_os = "macos") {
        utils::home_dir().join("Library/pnpm/store")
    } else {
        utils::home_dir().join(".local/share/pnpm/store")
    }
}
