package interceptor

import (
    "net/http"
    "os"

    "bindbox-game/configs"
    "bindbox-game/internal/code"
    "bindbox-game/internal/pkg/core"
    "bindbox-game/internal/pkg/jwtoken"
    "bindbox-game/internal/pkg/utils"
    "bindbox-game/internal/proposal"
    "bindbox-game/internal/repository/mysql/dao"

    "gorm.io/gorm"
)

func (i *interceptor) AdminTokenAuthVerify(ctx core.Context) (sessionUserInfo proposal.SessionUserInfo, err core.BusinessError) {
	headerAuthorizationString := ctx.GetHeader("Authorization")
	if headerAuthorizationString == "" {
		err = core.Error(
			http.StatusUnauthorized,
			code.JWTAuthVerifyError,
			"无法确认您的身份，请进行登录。")

		return
	}

	// 验证 JWT 是否合法
    secret := configs.Get().JWT.AdminSecret
    if v := os.Getenv("ADMIN_JWT_SECRET"); v != "" { secret = v }
    jwtClaims, jwtErr := jwtoken.New(secret).Parse(headerAuthorizationString)
	if jwtErr != nil {
		err = core.Error(
			http.StatusUnauthorized,
			code.JWTAuthVerifyError,
			"您的账号登录过期，请重新登录。")

		return
	}

	// 验证用户状态
	info, dbErr := dao.Use(i.db.GetDbR()).Admin.WithContext(ctx.RequestContext()).Where(dao.Use(i.db.GetDbR()).Admin.ID.Eq(jwtClaims.Id)).First()
	if dbErr != nil && dbErr != gorm.ErrRecordNotFound {
		err = core.Error(
			http.StatusUnauthorized,
			code.ServerError,
			"身份验证失败，如需帮助请联系我们。")

		return
	}

	if dbErr == gorm.ErrRecordNotFound {
		err = core.Error(
			http.StatusUnauthorized,
			code.ServerError,
			"无法确认您的身份，请进行登录。")

		return
	}

	if utils.MD5(headerAuthorizationString) != info.LastLoginHash {
		err = core.Error(
			http.StatusUnauthorized,
			code.JWTAuthVerifyError,
			"您的账号已在别处登录，为了保护您的账户安全，请重新登录。")
		return
	}

	// 验证登录状态
	if info.LoginStatus != 1 {
		err = core.Error(
			http.StatusUnauthorized,
			code.ServerError,
			"您的账号已被禁用，如需帮助请联系我们。").WithAlert()

		return
	}

	sessionUserInfo = jwtClaims.SessionUserInfo

	return
}
