use std::path::Path;

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

pub struct GatsbyPlugin;

impl Plugin for GatsbyPlugin {
    fn name(&self) -> &str {
        "gatsby"
    }

    fn description(&self) -> &str {
        "Gatsby build cache and output"
    }

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

        let has_gatsby_config =
            dir.join("gatsby-config.js").exists() || dir.join("gatsby-config.ts").exists();

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

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

        targets
    }

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