package gitaly

import (
	"context"
	"errors"
	"fmt"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/grpctool/test"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

var (
	_ error = &Error{}
)

func TestErrorUnwrap(t *testing.T) {
	e := &Error{
		Code:    RPCError,
		Cause:   context.Canceled,
		Message: "bla",
	}
	assert.Equal(t, context.Canceled, e.Unwrap())
	assert.ErrorIs(t, e, context.Canceled)
}

func TestErrorString(t *testing.T) {
	e := &Error{
		Code:    RPCError,
		Message: "bla",
	}
	assert.EqualError(t, e, "RPCError: bla")

	e = &Error{
		Code:    RPCError,
		Cause:   context.Canceled,
		Message: "bla",
	}
	assert.EqualError(t, e, "RPCError: bla: context canceled")

	e = &Error{
		Code:    RPCError,
		Cause:   context.Canceled,
		Message: "bla",
		Path:    "path",
	}
	assert.EqualError(t, e, "RPCError: bla: path: context canceled")

	e = &Error{
		Code:    RPCError,
		Message: "bla",
		Path:    "path",
	}
	assert.EqualError(t, e, "RPCError: bla: path")

	e = &Error{
		Code:    RPCError,
		Cause:   context.Canceled,
		Message: "bla",
		RPCName: "GetFoo",
		Path:    "path",
	}
	assert.EqualError(t, e, "RPCError: GetFoo: bla: path: context canceled")

	e = &Error{
		Code:    RPCError,
		Message: "bla",
		RPCName: "GetFoo",
		Path:    "path",
	}
	assert.EqualError(t, e, "RPCError: GetFoo: bla: path")

	e = &Error{
		Code:    RPCError,
		Message: "bla",
		Path:    "path",
	}
	assert.EqualError(t, e, "RPCError: bla: path")
}

func TestUnknownErrorCode(t *testing.T) {
	var e ErrorCode = -1
	assert.Equal(t, "invalid ErrorCode: -1", e.String())
}

func TestErrorCodeFromError(t *testing.T) {
	e := &Error{
		Code: RPCError,
	}
	assert.Equal(t, RPCError, ErrorCodeFromError(e))

	err := fmt.Errorf("%w", e)
	assert.Equal(t, RPCError, ErrorCodeFromError(err))

	err = errors.New("bla")
	assert.Equal(t, UnknownError, ErrorCodeFromError(err))
}

func TestErrorToGrpcError(t *testing.T) {
	e := &Error{
		Code:    RPCError,
		Cause:   status.Error(codes.DataLoss, "oh no"),
		Message: "msg",
		RPCName: test.Testing_RequestResponse_FullMethodName,
		Path:    "path",
	}

	s, ok := status.FromError(e)
	require.True(t, ok)
	assert.Equal(t, codes.DataLoss, s.Code())
	assert.Equal(t, "RPCError: /gitlab.agent.grpctool.test.Testing/RequestResponse: msg: path: rpc error: code = DataLoss desc = oh no", s.Message())
	assert.EqualError(t, s.Err(), "rpc error: code = DataLoss desc = RPCError: /gitlab.agent.grpctool.test.Testing/RequestResponse: msg: path: rpc error: code = DataLoss desc = oh no")
}
