pub type GitResult<T> = Result<T, GitError>;

#[derive(Debug, thiserror::Error)]
pub enum GitError {
    #[error("repository is not bare")]
    NotBareRepository,
    #[error("git command failed with status {status_code:?}: {stderr}")]
    CommandFailed {
        status_code: Option<i32>,
        stderr: String,
    },
    #[error("unsafe git command rejected: {0}")]
    UnsafeCommand(String),
    #[error("object not found: {0}")]
    ObjectNotFound(String),
    #[error("reference not found: {0}")]
    RefNotFound(String),
    #[error("parse error: {0}")]
    ParseError(String),
    #[error(transparent)]
    Io(#[from] std::io::Error),
    #[error("gix error: {0}")]
    Gix(String),
    #[error("database error: {0}")]
    DatabaseError(db::sqlx::Error),
    #[error("repository not found")]
    RepoNotFound,
    #[error("internal error: {0}")]
    Internal(String),
    #[error("not found: {0}")]
    NotFound(String),
    #[error("invalid oid: {0}")]
    InvalidOid(String),
    #[error("locked: {0}")]
    Locked(String),
    #[error("permission denied: {0}")]
    PermissionDenied(String),
    #[error("authentication failed: {0}")]
    AuthFailed(String),
}

impl From<db::sqlx::Error> for GitError {
    fn from(e: db::sqlx::Error) -> Self {
        GitError::DatabaseError(e)
    }
}

macro_rules! impl_gix_error {
    ($err_type:path) => {
        impl From<$err_type> for GitError {
            fn from(e: $err_type) -> Self {
                GitError::Gix(e.to_string())
            }
        }
    };
}

impl_gix_error!(gix::object::find::existing::Error);
impl_gix_error!(gix::object::find::existing::with_conversion::Error);
impl_gix_error!(gix::object::find::Error);
impl_gix_error!(gix::reference::iter::Error);
impl_gix_error!(gix::reference::iter::init::Error);
impl_gix_error!(gix::reference::find::existing::Error);
impl_gix_error!(gix::reference::find::Error);
impl_gix_error!(gix::reference::head_id::Error);
impl_gix_error!(gix::repository::merge_bases_many::Error);
impl_gix_error!(gix::reference::peel::Error);
impl_gix_error!(gix::repository::blame_file::Error);
impl_gix_error!(gix::blame::Error);
impl_gix_error!(gix::revision::walk::Error);
impl_gix_error!(gix::revision::walk::iter::Error);
impl_gix_error!(gix::revision::spec::parse::single::Error);
impl_gix_error!(gix::open::Error);
impl_gix_error!(gix::objs::decode::Error);
impl_gix_error!(gix::date::Error);

impl From<Box<dyn std::error::Error + Send + Sync>> for GitError {
    fn from(e: Box<dyn std::error::Error + Send + Sync>) -> Self {
        GitError::Gix(e.to_string())
    }
}
