package errors

import (
	"context"
	"errors"
	"strings"

	apistatus "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/client/status"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func UnwrapErr(err error) error {
	unwrappedErr := errors.Unwrap(err)
	for unwrappedErr != nil {
		err = unwrappedErr
		unwrappedErr = errors.Unwrap(err)
	}

	return err
}

func IsErrObjectAccessDenied(err error) (string, bool) {
	err = UnwrapErr(err)
	switch err := err.(type) {
	default:
		return "", false
	case *apistatus.ObjectAccessDenied:
		return err.Reason(), true
	}
}

func IsTimeoutError(err error) bool {
	if strings.Contains(err.Error(), "timeout") ||
		errors.Is(err, context.DeadlineExceeded) {
		return true
	}

	return status.Code(UnwrapErr(err)) == codes.DeadlineExceeded
}