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

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

pub struct PostgresPlugin;

impl Plugin for PostgresPlugin {
    fn name(&self) -> &str {
        "postgres"
    }

    fn description(&self) -> &str {
        "PostgreSQL data and WAL files"
    }

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

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

        // Homebrew PostgreSQL data directories
        for version in &["@14", "@15", "@16", "@17", ""] {
            let dir = format!("/opt/homebrew/var/postgresql{version}");
            let path = std::path::PathBuf::from(&dir);
            if path.is_dir() {
                let size = utils::dir_size(&path);
                targets.push(CleanTarget {
                    label: format!("{}", path.display()),
                    size_bytes: size,
                    action: CleanAction::DeletePath(path),
                    plugin_name: self.name().to_string(),
                    safety: Safety::Unsafe,
                    explanation: "PostgreSQL data directory, contains all databases".to_string(),
                });
            }
        }

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

        targets
    }

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