use crate::app::{actions::Action, state::AppState};
use crate::app::state::AsyncTaskStatus;

pub fn reduce(mut state: AppState, action: &Action) -> Option<AppState> {
    match action {
        Action::AddAsyncTask(task) => {
            state.async_tasks.push(task.clone());
        }
        Action::CompleteAsyncTask(id) => {
            if let Some(task) = state.async_tasks.iter_mut().find(|t| t.id == *id) {
                task.status = AsyncTaskStatus::Completed;
            }
        }
        Action::FailAsyncTask(id, error) => {
            if let Some(task) = state.async_tasks.iter_mut().find(|t| t.id == *id) {
                task.status = AsyncTaskStatus::Failed(error.clone());
            }
        }
        Action::CleanupAsyncTasks => {
            state.async_tasks.retain(|t| {
                matches!(t.status, AsyncTaskStatus::Running)
                    || t.started_at.elapsed().as_secs() < 5
            });
        }
        _ => return None,
    }
    Some(state)
}
