package interceptor

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

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
	"github.com/tidbcloud/observability/pkg/globalservice/structs"
	mock_meta_manager "github.com/tidbcloud/observability/test/mockmetamanager"
	"go.uber.org/mock/gomock"
)

func Test_UserAuth(t *testing.T) {
	ctrl := gomock.NewController(t)
	cacheGetter := mock_meta_manager.NewMockMetaCacheGetter(ctrl)
	cacheGetter.EXPECT().GetGlobalMetaCache().Return(
		&structs.GlobalServiceMeta{
			ServerConfig: structs.ServerConfig{
				BizToAccountProviderSvcAddr: map[string]string{
					"tidbcloud":     "test:10000",
					"dev-tidbcloud": "test-dev:10000",
				}},
		},
	).AnyTimes()
	metaCacheGetter = cacheGetter

	t.Run("unauthorized: bad token", func(t *testing.T) {

		gin.SetMode(gin.TestMode)
		w := httptest.NewRecorder()
		c, _ := gin.CreateTestContext(w)
		c.Request = &http.Request{
			Header: map[string][]string{
				"Authorization": {"12312422141"},
				"Content-Type":  {"application/json"},
			},
			URL: &url.URL{
				Path: "/api/v1/external/tidbcloud/orgs/1/projects/1/clusters/1/alerts",
			},
		}

		UserAuth(c)

		assert.Equal(t, http.StatusUnauthorized, w.Code)
	})

	t.Run("unauthorized: bad bizType", func(t *testing.T) {
		gin.SetMode(gin.TestMode)
		w := httptest.NewRecorder()
		c, _ := gin.CreateTestContext(w)
		c.Request = &http.Request{
			Header: map[string][]string{
				"Authorization": {"Bearer 12312422141"},
				"Content-Type":  {"application/json"},
			},
			URL: &url.URL{
				Path: "/api/v1/external/tidbcloud-dev/orgs/1/projects/1/clusters/1/alerts",
			},
		}

		UserAuth(c)
		assert.Equal(t, http.StatusUnauthorized, w.Code)
	})
}
