package streaming

import (
	"context"
	"net"
	"testing"

	"github.com/tidbcloud/service-proxy/pkg/checker/core"
)

func TestPulsarChecker_Check(t *testing.T) {
	lis, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("listen error: %v", err)
	}
	t.Cleanup(func() { _ = lis.Close() })

	address := "pulsar://" + lis.Addr().String()

	tests := []struct {
		name    string
		ctx     context.Context
		params  *core.PulsarParams
		wantErr bool
	}{
		{
			name: "reachable broker with token auth",
			ctx:  context.Background(),
			params: &core.PulsarParams{
				ServiceURL:        address,
				AuthType:          core.PulsarAuthTypeToken,
				Token:             "test-token",
				ConnectionTimeout: 1,
			},
			wantErr: false,
		},
		{
			name: "unreachable broker",
			ctx:  context.Background(),
			params: &core.PulsarParams{
				ServiceURL:        "pulsar://127.0.0.1:1",
				AuthType:          core.PulsarAuthTypeToken,
				Token:             "test-token",
				ConnectionTimeout: 1,
			},
			wantErr: true,
		},
		{
			name: "context cancelled",
			ctx: func() context.Context {
				ctx, cancel := context.WithCancel(context.Background())
				cancel()
				return ctx
			}(),
			params: &core.PulsarParams{
				ServiceURL:        address,
				AuthType:          core.PulsarAuthTypeToken,
				Token:             "test-token",
				ConnectionTimeout: 1,
			},
			wantErr: true,
		},
		{
			name: "no auth type (should fail)",
			ctx:  context.Background(),
			params: &core.PulsarParams{
				ServiceURL:        address,
				AuthType:          "",
				ConnectionTimeout: 1,
			},
			wantErr: true,
		},
		{
			name: "basic auth missing credentials",
			ctx:  context.Background(),
			params: &core.PulsarParams{
				ServiceURL:        address,
				AuthType:          core.PulsarAuthTypeBasic,
				ConnectionTimeout: 1,
			},
			wantErr: true,
		},
		{
			name: "token auth missing token",
			ctx:  context.Background(),
			params: &core.PulsarParams{
				ServiceURL:        address,
				AuthType:          core.PulsarAuthTypeToken,
				ConnectionTimeout: 1,
			},
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			c := NewPulsarChecker(tt.params)
			err := c.Check(tt.ctx)

			if tt.wantErr && err == nil {
				t.Fatal("expected error, got nil")
			}

			if !tt.wantErr && err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
		})
	}
}
