use anyhow::{bail, Result};
use std::process::Command;

use crate::git::cli::GitCli;

impl GitCli {
    pub fn reflog(&self, repo_path: &str, limit: usize) -> Result<Vec<crate::app::state::ReflogEntry>> {
        let output = Command::new("git")
            .args([
                "-C", repo_path,
                "reflog", "--date=relative",
                &format!("-n{}", limit),
                "--format=%h|%gd|%gs|%cr"
            ])
            .output()?;

        if !output.status.success() {
            bail!(
                "git reflog failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }

        let text = String::from_utf8_lossy(&output.stdout);
        let mut entries = Vec::new();
        for line in text.lines() {
            let parts: Vec<&str> = line.splitn(4, '|').collect();
            if parts.len() == 4 {
                entries.push(crate::app::state::ReflogEntry {
                    short_hash: parts[0].to_string(),
                    selector: parts[1].to_string(),
                    action: parts[2].to_string(),
                });
            }
        }
        Ok(entries)
    }
}
