use crate::{
    bare::GitBare,
    cmd::merge::{MergeAnalysisResult, MergePreferenceResult},
    errors::{GitError, GitResult},
};

impl GitBare {
    pub fn merge_analysis_for_ref(
        &self,
        ref_name: String,
    ) -> GitResult<(MergeAnalysisResult, MergePreferenceResult)> {
        let repo = self.gix_repo()?;
        let their_id =
            repo.rev_parse_single(ref_name.as_str()).map_err(|_| {
                GitError::RefNotFound(format!(
                    "reference '{}' could not be resolved",
                    ref_name
                ))
            })?;
        let their_gix_id = their_id.detach();

        let head_id = repo.head_id()?;
        let head_gix_id = head_id.detach();
        let is_up_to_date = repo
            .merge_base(their_gix_id, head_gix_id)
            .ok()
            .is_some_and(|base| base.detach() == their_gix_id);

        if is_up_to_date {
            return Ok((
                MergeAnalysisResult {
                    is_none: false,
                    is_normal: false,
                    is_up_to_date: true,
                    is_fast_forward: false,
                    is_unborn: false,
                },
                MergePreferenceResult {
                    is_none: false,
                    is_no_fast_forward: false,
                    is_fastforward_only: false,
                },
            ));
        }
        let is_fast_forward = repo
            .merge_base(head_gix_id, their_gix_id)
            .ok()
            .is_some_and(|base| base.detach() == head_gix_id);

        if is_fast_forward {
            return Ok((
                MergeAnalysisResult {
                    is_none: false,
                    is_normal: false,
                    is_up_to_date: false,
                    is_fast_forward: true,
                    is_unborn: false,
                },
                MergePreferenceResult {
                    is_none: false,
                    is_no_fast_forward: false,
                    is_fastforward_only: false,
                },
            ));
        }
        Ok((
            MergeAnalysisResult {
                is_none: false,
                is_normal: true,
                is_up_to_date: false,
                is_fast_forward: false,
                is_unborn: false,
            },
            MergePreferenceResult {
                is_none: false,
                is_no_fast_forward: false,
                is_fastforward_only: false,
            },
        ))
    }
}
