package api

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

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/require"
	"github.com/tidbcloud/aisupport/services/oncall/service"
)

func TestInternalNoAuthMiddleware(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name         string
		email        string
		operator     string
		wantEmail    string
		wantUserName string
	}{
		{
			name:         "default service principal",
			wantEmail:    "oncall-internal@pingcap.com",
			wantUserName: "oncall-internal",
		},
		{
			name:         "caller supplied identity",
			email:        " Caller@PingCAP.com ",
			operator:     "eks-client",
			wantEmail:    "caller@pingcap.com",
			wantUserName: "eks-client",
		},
	}

	for _, test := range tests {
		test := test
		t.Run(test.name, func(t *testing.T) {
			t.Parallel()

			r := gin.New()
			r.Use(InternalNoAuthMiddleware())
			r.Use(ServiceKeyScopeGuard())
			r.POST("/api/v1/oncall/test", func(c *gin.Context) {
				c.JSON(http.StatusOK, gin.H{
					"email":  c.GetString("request_user_email"),
					"name":   c.GetString("request_user_name"),
					"scopes": c.GetString("api_scopes"),
				})
			})

			req := httptest.NewRequest(http.MethodPost, "/api/v1/oncall/test", nil)
			if test.email != "" {
				req.Header.Set("X-User-Email", test.email)
			}
			if test.operator != "" {
				req.Header.Set("X-Operator", test.operator)
			}
			resp := httptest.NewRecorder()
			r.ServeHTTP(resp, req)

			require.Equal(t, http.StatusOK, resp.Code, resp.Body.String())
			require.JSONEq(t, `{
				"email": "`+test.wantEmail+`",
				"name": "`+test.wantUserName+`",
				"scopes": "`+service.ScopeOncallRead+` `+service.ScopeOncallWrite+`"
			}`, resp.Body.String())
		})
	}
}
