package api

import (
	"net/http"

	"github.com/tidbcloud/account/internel/svc/user"

	"github.com/tidbcloud/account/internel/dao/entity"

	"github.com/tidbcloud/account/central/server"
	"github.com/tidbcloud/account/commons/config"

	"github.com/gin-gonic/gin"
	"github.com/tidbcloud/account/central/utils"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"github.com/tidbcloud/tiinf/sdk/auth"
	"go.uber.org/zap"
)

// create swag doc command: make generate_openapi_docs

// @title User OPENAPI
// @version v1beta1
// @description This is the user related API.
// @host iam.tidbapi.com

func RegisterUserRouter(e gin.IRouter) {

	r := e.Group("/v1beta1/user")

	r.Use(server.LocalTestIdentity)
	if !config.IsLocalEnv() {

		//pathWhitelist := []string{"/v1beta1/user/userinfo"}
		auth.InitAccountClientByEndpoint(config.Global().GrpcConfig.AccountSvcAddr, 0)

		r.Use(
			auth.GinGetIdentityInfoInterceptor(&auth.IdentityAuthOption{
				EnableLog: true,
			}),
		)

	}

	r.GET("/userinfo", UserInfoHandler)

}

// https://iam.tidbapi.com/v1beta1/user/userinfo
// @Tags Account
// @Summary Query sql user
// @Description  This endpoint return user information
// @Schemes
// @Accept json
// @Produce json
// @Success 200 {object} UserInfo
// @Failure 400  {object}  OpenApiError
// @Router /v1beta1/user/userinfo [GET]
func UserInfoHandler(c *gin.Context) {
	ctx := c.Request.Context()
	bm := utils.Begin(ctx, "QuerySqlUserHandler")
	defer bm.OnExit(ctx)

	tilog.Info(ctx, "UserInfoHandler")

	authInfo, err := auth.GetIdentityInfoFromGinContext(c)
	if err != nil {
		tilog.Info(ctx, "get auth Info failed %v", zap.Error(err))
	}

	userInfo := UserInfo{}
	var entityUser *entity.User

	// 1、call by access token
	if authInfo.IdentityType == auth.AuthnIdentityTypeAccessToken {
		userId := authInfo.AccessTokenRsp.AccessTokenIdentity.UserId
		email := authInfo.AccessTokenRsp.AccessTokenIdentity.UserEmail
		tilog.Info(ctx, "get access token info", zap.Any("userId", userId), zap.Any("email", email))

		svc, _ := user.GetUserSvc()

		entityUser, err = svc.GetUserByEmail(ctx, email)

		// 2、call by apikey
	} else if authInfo.IdentityType == auth.AuthnIdentityTypeApiKeyAK {
		return
	}
	if err != nil {
		tilog.Info(ctx, "ListProject err", zap.Error(err))
		writeError(ctx, c.Writer, err, http.StatusInternalServerError, internalServerErrorCode, "internal server error")
		return
	}
	if entityUser != nil {
		userInfo.FirstName = entityUser.FirstName
		userInfo.LastName = entityUser.LastName
		userInfo.Email = entityUser.Email
		userInfo.Username = entityUser.FirstName + entityUser.LastName
	}

	tilog.Info(ctx, "UserInfoHandler result", zap.Any("userInfo", userInfo))
	openApiWriteResult(c.Writer, userInfo)

}
