use std::path::Path;

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

pub struct WebpackPlugin;

impl Plugin for WebpackPlugin {
    fn name(&self) -> &str {
        "webpack"
    }

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

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

        let has_webpack_config = dir.join("webpack.config.js").exists()
            || dir.join("webpack.config.ts").exists()
            || dir.join("webpack.config.mjs").exists();

        if has_webpack_config {
            let dist = dir.join("dist");
            if dist.is_dir() {
                let size = utils::dir_size(&dist);
                targets.push(CleanTarget {
                    label: format!("{}", dist.display()),
                    size_bytes: size,
                    action: CleanAction::DeletePath(dist),
                    plugin_name: self.name().to_string(),
                    safety: Safety::Recoverable,
                    explanation: "Webpack build output, regenerated with `webpack build`"
                        .to_string(),
                });
            }
        }

        targets
    }

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