use std::path::Path;

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

pub struct EsbuildPlugin;

impl Plugin for EsbuildPlugin {
    fn name(&self) -> &str {
        "esbuild"
    }

    fn description(&self) -> &str {
        "esbuild build output"
    }

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

        let has_esbuild_config = dir.join("esbuild.config.js").exists()
            || dir.join("esbuild.config.ts").exists()
            || dir.join("esbuild.config.mjs").exists();

        if has_esbuild_config {
            for name in ["dist", "out"] {
                let path = dir.join(name);
                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::Recoverable,
                        explanation: "esbuild build output, regenerated on next build".to_string(),
                    });
                }
            }
        }

        targets
    }

    fn markers(&self) -> &'static [&'static str] {
        &[
            "esbuild.config.js",
            "esbuild.config.ts",
            "esbuild.config.mjs",
        ]
    }
}
