use std::path::Path;
use std::process::Command;

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

pub struct MysqlPlugin;

impl Plugin for MysqlPlugin {
    fn name(&self) -> &str {
        "mysql"
    }

    fn description(&self) -> &str {
        "MySQL / MariaDB data files"
    }

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

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

        // Homebrew MySQL data directory
        let brew_dir = std::path::PathBuf::from("/opt/homebrew/var/mysql");
        if brew_dir.is_dir() {
            let size = utils::dir_size(&brew_dir);
            targets.push(CleanTarget {
                label: format!("{}", brew_dir.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(brew_dir),
                plugin_name: self.name().to_string(),
                safety: Safety::Unsafe,
                explanation: "MySQL data directory, contains all databases".to_string(),
            });
        }

        // Linux default data directory
        let linux_dir = std::path::PathBuf::from("/var/lib/mysql");
        if linux_dir.is_dir() {
            let size = utils::dir_size(&linux_dir);
            targets.push(CleanTarget {
                label: format!("{}", linux_dir.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(linux_dir),
                plugin_name: self.name().to_string(),
                safety: Safety::Unsafe,
                explanation: "MySQL data directory, contains all databases".to_string(),
            });
        }

        targets
    }

    fn is_available(&self) -> bool {
        Command::new("mysql")
            .arg("--version")
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    }
}
