use crate::{bare::GitBare, errors::GitResult};

impl GitBare {
    pub fn branch_head_name(&self) -> GitResult<String> {
        let repo = self.gix_repo()?;
        let head_name = repo.head_name()?;
        match head_name {
            Some(name) => Ok(name.shorten().to_string()),
            None => {
                Err(crate::errors::GitError::RefNotFound("HEAD".to_string()))
            }
        }
    }

    pub fn branch_ahead_behind(&self, branch_name: String) -> GitResult<bool> {
        let upstream = self.branch_upstream_name(branch_name.clone())?;
        let upstream_name = match upstream {
            Some(name) => name,
            None => return Ok(false),
        };

        let repo = self.gix_repo()?;
        let branch_id = repo
            .rev_parse_single(branch_name.as_str())
            .map_err(|_| crate::errors::GitError::RefNotFound(branch_name))?;
        let upstream_id = repo
            .rev_parse_single(upstream_name.as_str())
            .map_err(|_| crate::errors::GitError::RefNotFound(upstream_name))?;

        let branch_commit = branch_id.detach();
        let upstream_commit = upstream_id.detach();
        let merge_base = repo.merge_base(branch_commit, upstream_commit).ok();

        Ok(merge_base.is_some_and(|base| base.detach() != branch_commit))
    }
}
