package grpctool

import (
	"context"
	"log/slog"
	"testing"

	"github.com/golang-jwt/jwt/v5"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/grpctool/test"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/testing/testlogger"
	"gitlab.com/gitlab-org/cluster-integration/tunnel/tool/grpcz"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/credentials/insecure"
	"k8s.io/apimachinery/pkg/util/wait"
)

var (
	_ credentials.PerRPCCredentials = &JWTCredentials{}
)

const (
	secret   = "dfjnfkadskfadsnfkjadsgkasdbg"
	audience = "fasfadsf"
	issuer   = "cbcxvbvxbxb"
)

func TestJWTCredentialsProducesValidToken(t *testing.T) {
	c := &JWTCredentials{
		SigningMethod: jwt.SigningMethodHS256,
		SigningKey:    []byte(secret),
		Audience:      audience,
		Issuer:        issuer,
		Insecure:      true,
	}
	auther := NewHMACJWTAuther([]byte(secret), issuer, audience, func(ctx context.Context) *slog.Logger { //nolint: misspell
		return testlogger.New(t)
	})
	listener := grpcz.NewPipeDialListener()

	srv := grpc.NewServer(
		grpc.ChainStreamInterceptor(
			auther.StreamServerInterceptor, //nolint: misspell
		),
		grpc.ChainUnaryInterceptor(
			auther.UnaryServerInterceptor, //nolint: misspell
		),
	)
	test.RegisterTestingServer(srv, &test.GRPCTestingServer{
		UnaryFunc: func(ctx context.Context, request *test.Request) (*test.Response, error) {
			return &test.Response{
				Message: &test.Response_Scalar{Scalar: 123},
			}, nil
		},
		StreamingFunc: func(server grpc.BidiStreamingServer[test.Request, test.Response]) error {
			return server.Send(&test.Response{
				Message: &test.Response_Scalar{Scalar: 123},
			})
		},
	})
	var wg wait.Group
	defer wg.Wait()
	defer srv.GracefulStop()
	wg.Start(func() {
		assert.NoError(t, srv.Serve(listener))
	})
	conn, err := grpc.NewClient("passthrough:pipe",
		grpc.WithContextDialer(listener.DialContext),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithPerRPCCredentials(c),
	)
	require.NoError(t, err)
	defer conn.Close()
	client := test.NewTestingClient(conn)
	_, err = client.RequestResponse(context.Background(), &test.Request{})
	require.NoError(t, err)
	stream, err := client.StreamingRequestResponse(context.Background())
	require.NoError(t, err)
	_, err = stream.Recv()
	require.NoError(t, err)
}
