use tonic::Status;

use crate::errors::GitError;

pub fn to_status(err: GitError) -> Status {
    match err {
        GitError::NotBareRepository => {
            Status::not_found("not a bare repository")
        }
        GitError::CommandFailed {
            status_code,
            stderr,
        } => {
            let msg = format!(
                "git command failed (status={status_code:?}): {stderr}"
            );
            Status::internal(msg)
        }
        GitError::UnsafeCommand(cmd) => {
            Status::invalid_argument(format!("unsafe command: {cmd}"))
        }
        GitError::ObjectNotFound(oid) => {
            Status::not_found(format!("object not found: {oid}"))
        }
        GitError::RefNotFound(ref_name) => {
            Status::not_found(format!("ref not found: {ref_name}"))
        }
        GitError::ParseError(msg) => {
            Status::internal(format!("parse error: {msg}"))
        }
        GitError::Io(e) => Status::internal(format!("io error: {e}")),
        GitError::DatabaseError(e) => {
            Status::internal(format!("database error{e}"))
        }
        GitError::RepoNotFound => Status::not_found("repo not found"),
        GitError::Internal(msg) => Status::internal(msg),
        GitError::NotFound(msg) => Status::not_found(msg),
        GitError::InvalidOid(msg) => Status::invalid_argument(msg),
        GitError::Locked(msg) => Status::failed_precondition(msg),
        GitError::PermissionDenied(msg) => Status::permission_denied(msg),
        GitError::AuthFailed(msg) => Status::unauthenticated(msg),
        GitError::Gix(msg) => Status::internal(format!("gix error: {msg}")),
    }
}

pub fn spawn_blocking_error(e: tokio::task::JoinError) -> Status {
    Status::internal(format!("spawn_blocking failed: {e}"))
}
