use std::path::Path;

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

pub struct YarnPlugin;

impl Plugin for YarnPlugin {
    fn name(&self) -> &str {
        "yarn"
    }

    fn description(&self) -> &str {
        "Yarn berry cache and classic global cache"
    }

    fn scan_directory(&self, dir: &Path) -> Vec<CleanTarget> {
        let mut targets = Vec::new();

        if dir.join("yarn.lock").exists() {
            let yarn_cache = dir.join(".yarn/cache");
            if yarn_cache.is_dir() {
                let size = utils::dir_size(&yarn_cache);
                targets.push(CleanTarget {
                    label: format!("{}", yarn_cache.display()),
                    size_bytes: size,
                    action: CleanAction::DeletePath(yarn_cache),
                    plugin_name: self.name().to_string(),
                    safety: Safety::Recoverable,
                    explanation: "Yarn package cache, reinstall with `yarn install`".to_string(),
                });
            }
        }

        targets
    }

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

        // Yarn v1 classic cache
        let yarn_cache = home.join(".cache/yarn");
        if yarn_cache.is_dir() {
            let size = utils::dir_size(&yarn_cache);
            targets.push(CleanTarget {
                label: format!("{}", yarn_cache.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(yarn_cache),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "Yarn global cache, re-downloaded as needed".to_string(),
            });
        }

        #[cfg(target_os = "macos")]
        {
            let yarn_mac_cache = home.join("Library/Caches/Yarn");
            if yarn_mac_cache.is_dir() {
                let size = utils::dir_size(&yarn_mac_cache);
                targets.push(CleanTarget {
                    label: format!("{}", yarn_mac_cache.display()),
                    size_bytes: size,
                    action: CleanAction::DeletePath(yarn_mac_cache),
                    plugin_name: self.name().to_string(),
                    safety: Safety::Recoverable,
                    explanation: "Yarn Berry cache, re-downloaded as needed".to_string(),
                });
            }
        }

        targets
    }

    fn markers(&self) -> &'static [&'static str] {
        &["yarn.lock"]
    }
}
