use std::path::Path;

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

pub struct ComposerPlugin;

impl Plugin for ComposerPlugin {
    fn name(&self) -> &str {
        "composer"
    }

    fn description(&self) -> &str {
        "PHP Composer vendor dependencies and cache"
    }

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

        let composer_json = dir.join("composer.json");
        if composer_json.exists() {
            let vendor = dir.join("vendor");
            if vendor.is_dir() {
                let size = utils::dir_size(&vendor);
                targets.push(CleanTarget {
                    label: format!("{}", vendor.display()),
                    size_bytes: size,
                    action: CleanAction::DeletePath(vendor),
                    plugin_name: self.name().to_string(),
                    safety: Safety::Recoverable,
                    explanation: "PHP dependencies, reinstall with `composer install`".to_string(),
                });
            }
        }

        targets
    }

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

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

        targets
    }

    fn skip_subdirectories(&self) -> &'static [&'static str] {
        &["vendor"]
    }

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