//! Reset commands.
//!
//! Handles Git reset operations (soft, mixed, hard).

use crate::commands::{Command, CommandResult};
use crate::services::GitService;
use crate::app::{AppState, Action, reducer};
use crate::errors::CommandError;
use tracing::instrument;

/// Reset to target with mode
pub struct ResetCommand {
    pub mode: &'static str, // "--soft", "--mixed", "--hard"
    pub target: String,
}

impl Command for ResetCommand {
    #[instrument(skip(self, git, state), fields(mode = %self.mode, target = %self.target))]
    fn execute(
        &self,
        git: &GitService,
        state: &AppState,
    ) -> Result<CommandResult, CommandError> {
        let mut new_state = state.clone();
        let label = match self.mode {
            "--soft" => "reset --soft",
            "--mixed" => "reset --mixed",
            "--hard" => "reset --hard",
            other => other,
        };
        new_state = reducer(new_state, Action::SetOpStatus(Some(format!("{label}…"))));
        match git.reset(&state.repo_path, self.mode, &self.target) {
            Ok(_) => {
                new_state = reducer(new_state, Action::SetFeedback(Some(format!("Reset {} {}", self.mode, self.target))));
                new_state = reducer(new_state, Action::SetRefreshing(true));
                new_state = reducer(new_state, Action::AppendOpLog(format!("{label} {}", self.target)));
                new_state = reducer(
                    new_state,
                    Action::AppendOpLog(
                        "Reset done. Push with --force-with-lease (P) if this branch is shared.".into(),
                    ),
                );
                new_state = reducer(
                    new_state,
                    Action::SetOpStatus(Some(
                        "Reset done. Push with --force-with-lease (P) if shared.".into(),
                    )),
                );
            }
            Err(e) => {
                new_state = reducer(new_state, Action::AppendOpLog(format!("reset error: {e}")));
                new_state = reducer(new_state, Action::SetStatusError(Some(format!("reset error: {e}"))));
            }
        }
        new_state = reducer(new_state, Action::SetOpStatus(None));
        Ok(CommandResult::StateUpdate(new_state))
    }
}

