use crate::{
    bare::GitBare,
    cmd::oid::ObjectId,
    errors::{GitError, GitResult},
};

impl GitBare {
    pub fn merge_base_octopus(
        &self,
        commits: Vec<ObjectId>,
    ) -> GitResult<ObjectId> {
        if commits.len() < 2 {
            return Err(GitError::ParseError(
                "merge_base_octopus requires at least 2 commits".to_string(),
            ));
        }

        let repo = self.gix_repo()?;
        let gix_commits: Vec<gix::hash::ObjectId> = commits
            .iter()
            .map(|id| id.try_into())
            .collect::<Result<Vec<_>, _>>()?;

        let base = repo.merge_base_octopus(gix_commits).map_err(|_| {
            GitError::ObjectNotFound(
                "no octopus merge base found for the given commits".to_string(),
            )
        })?;

        Ok(ObjectId::new(base.detach().to_hex().to_string()))
    }
}
