use anyhow::Result;
use serde::Serialize;
use crate::db::Database;
use crate::models::{Goal, GoalState};
#[derive(Debug, Serialize)]
pub struct CleanResult {
pub candidates: usize,
pub removed: Vec<Goal>,
pub purge: bool,
pub force: bool,
}
pub fn run(
all: bool,
force: bool,
purge: bool,
db: &mut Database,
mut confirm: impl FnMut(&Goal, bool) -> Result<bool>,
mut on_removed: impl FnMut(&Goal, bool) -> Result<()>,
) -> Result<CleanResult> {
let goals: Vec<_> = db
.list_goals()
.into_iter()
.filter(|g| force || g.state() == GoalState::Completed || g.state() == GoalState::Cancelled)
.cloned()
.collect();
let candidates = goals.len();
let mut removed = Vec::new();
for goal in goals {
let should_remove = all || force || confirm(&goal, purge)?;
if should_remove {
if purge {
db.delete_goal(goal.id())?;
} else {
db.archive_goal(goal.id())?;
}
on_removed(&goal, purge)?;
removed.push(goal);
}
}
Ok(CleanResult {
candidates,
removed,
purge,
force,
})
}