package grpcerror

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"github.com/tidbcloud/tidb-management-service/utilities/bizerr"
)

func TestGenerateGRPCErrorMapsFailedPreconditionToBadRequest(t *testing.T) {
	const message = "resource pool is used by some clusters, cannot be deleted"
	const publicMessage = "Resource pool is used by some clusters, cannot be deleted."

	err := generateGRPCError(
		context.Background(),
		httptest.NewRequest(http.MethodDelete, "/v1beta2/resourcePools/42", http.NoBody),
		status.New(codes.FailedPrecondition, message),
	)

	var httpStatusError *runtime.HTTPStatusError
	require.ErrorAs(t, err, &httpStatusError)
	require.Equal(t, http.StatusBadRequest, httpStatusError.HTTPStatus)
	require.Equal(t, publicMessage, status.Convert(httpStatusError.Err).Message())
}

func TestGenerateGRPCErrorPreservesPrivateLinkPreconditionStatus(t *testing.T) {
	const message = "all IPv6 PrivateLink connections must be deleted first"
	const publicMessage = "All IPv6 PrivateLink connections must be deleted first."
	err := generateGRPCError(
		context.Background(),
		httptest.NewRequest(
			http.MethodPatch,
			"/v1beta1/clusters/11/tidbNodeGroups/22/privateLinkIpAddressTypeSetting",
			http.NoBody,
		),
		status.New(codes.Code(bizerr.ErrCodePrivateLinkIPAddressTypePrecondition), message),
	)

	var httpStatusError *runtime.HTTPStatusError
	require.ErrorAs(t, err, &httpStatusError)
	require.Equal(t, http.StatusPreconditionFailed, httpStatusError.HTTPStatus)
	require.Equal(t, publicMessage, status.Convert(httpStatusError.Err).Message())
}
