use std::path::Path;

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

pub struct TerraformPlugin;

impl Plugin for TerraformPlugin {
    fn name(&self) -> &str {
        "terraform"
    }

    fn description(&self) -> &str {
        "Terraform provider cache and plugin directories"
    }

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

        let tf_dir = dir.join(".terraform");
        if tf_dir.is_dir() {
            let size = utils::dir_size(&tf_dir);
            targets.push(CleanTarget {
                label: format!("{}", tf_dir.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(tf_dir),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "Terraform providers, reinstall with `terraform init`".to_string(),
            });
        }

        targets
    }

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

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

        targets
    }

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

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