use crate::{
    bare::GitBare, cmd::branch::branch_list::BranchListItem, errors::GitResult,
};

impl GitBare {
    pub fn branch_upstream_name(
        &self,
        branch_name: String,
    ) -> GitResult<Option<String>> {
        let repo = self.gix_repo()?;
        let ref_str = format!("refs/heads/{branch_name}");
        let reference = repo.find_reference(ref_str.as_str())?;

        let upstream = reference
            .remote_tracking_ref_name(gix::remote::Direction::Fetch)
            .and_then(|r| r.ok())
            .map(|n| n.shorten().to_string());

        Ok(upstream)
    }

    pub fn branch_upstream(
        &self,
        branch_name: String,
    ) -> GitResult<Option<BranchListItem>> {
        let upstream_name = self.branch_upstream_name(branch_name)?;
        match upstream_name {
            Some(name) => {
                let info = self.branch_info(name)?;
                Ok(Some(info))
            }
            None => Ok(None),
        }
    }

    pub fn branch_has_upstream(&self, branch_name: String) -> GitResult<bool> {
        let upstream = self.branch_upstream_name(branch_name)?;
        Ok(upstream.is_some())
    }
}
