use std::path::Path;

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

pub struct SqlitePlugin;

impl Plugin for SqlitePlugin {
    fn name(&self) -> &str {
        "sqlite"
    }

    fn description(&self) -> &str {
        "SQLite temporary and WAL files"
    }

    fn scans_all_directories(&self) -> bool {
        true
    }

    fn scan_with_entries(&self, _dir: &Path, entries: &[DirChild]) -> Vec<CleanTarget> {
        let mut targets = Vec::new();

        // Look for WAL and journal files that can safely be removed when the database is not in use
        for child in entries {
            if !child.is_file {
                continue;
            }

            let is_wal = child.name.ends_with("-wal");
            let is_shm = child.name.ends_with("-shm");

            if !is_wal && !is_shm {
                continue;
            }

            let size = child
                .path
                .metadata()
                .map(|m| utils::physical_size(&m))
                .unwrap_or(0);

            targets.push(CleanTarget {
                label: format!("{}", child.path.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(child.path.clone()),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "SQLite WAL/SHM file, regenerated automatically on next access"
                    .to_string(),
            });
        }

        targets
    }
}
