use std::path::Path;

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

pub struct NodeGypPlugin;

impl Plugin for NodeGypPlugin {
    fn name(&self) -> &str {
        "node-gyp"
    }

    fn description(&self) -> &str {
        "node-gyp Node.js headers and build 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 = node_gyp_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: "node-gyp native addon build cache".to_string(),
            });
        }

        targets
    }

    fn is_available(&self) -> bool {
        node_gyp_cache_dir().is_dir()
    }
}

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