package controller

import (
	"fmt"
	"time"

	"be.ems/src/framework/constants"
	"be.ems/src/framework/i18n"
	"be.ems/src/framework/reqctx"
	"be.ems/src/framework/resp"
	"be.ems/src/framework/token"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/modules/auth/service"
	systemService "be.ems/src/modules/system/service"

	"github.com/gin-gonic/gin"
)

// 实例化控制层 AccountController 结构体
var NewAccount = &AccountController{
	accountService:     service.NewAccount,
	sysLogLoginService: systemService.NewSysLogLogin,
}

// 账号身份操作处理
//
// PATH /
type AccountController struct {
	accountService     *service.Account           // 账号身份操作服务
	sysLogLoginService *systemService.SysLogLogin // 系统登录访问
}

// Logout 系统登出
//
// POST /auth/logout
func (s AccountController) Logout(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	tokenStr := reqctx.Authorization(c)
	if tokenStr != "" {
		// 存在token时记录退出信息
		userName, err := token.UserInfoRemove(tokenStr)
		if err != nil {
			// 当前请求信息
			ipaddr, location := reqctx.IPAddrLocation(c)
			os, browser := reqctx.UaOsBrowser(c)
			// 创建系统访问记录
			s.sysLogLoginService.Insert(
				userName, constants.STATUS_YES, "app.common.logoutSuccess",
				[4]string{ipaddr, location, os, browser},
			)
		}
	}
	c.JSON(200, resp.OkMsg(i18n.TKey(language, "app.common.logoutSuccess")))
}

// RefreshToken 刷新Token
//
// POST /auth/refresh-token
func (s AccountController) RefreshToken(c *gin.Context) {
	var body struct {
		RefreshToken string `json:"refreshToken" binding:"required"` // 刷新令牌
	}
	if err := c.ShouldBindJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}

	// 验证刷新令牌是否有效
	claims, err := token.UserTokenVerify(body.RefreshToken, "refresh")
	if err != nil {
		c.JSON(401, resp.CodeMsg(resp.CODE_AUTH_INVALID, err.Error()))
		return
	}
	userId := parse.Number(claims[constants.JWT_USER_ID])

	// 登录用户信息
	info, err := s.accountService.ByUserId(userId)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}

	// 设备指纹信息是否一致
	deviceId := fmt.Sprint(claims[constants.JWT_DEVICE_ID])
	deviceFingerprint := reqctx.DeviceFingerprint(c, userId)
	if deviceId != deviceFingerprint {
		c.JSON(401, resp.CodeMsg(resp.CODE_AUTH_DEVICE, resp.MSG_AUTH_DEVICE))
		return
	}

	// 生成访问令牌
	accessToken, expiresIn := token.UserTokenCreate(userId, deviceFingerprint, "access")
	if accessToken == "" || expiresIn == 0 {
		c.JSON(200, resp.ErrMsg("token generation failed"))
		return
	}
	// 生成刷新令牌
	now := time.Now()
	exp, _ := claims.GetExpirationTime()
	iat, _ := claims.GetIssuedAt()
	refreshExpiresIn := int64(exp.Sub(now).Seconds())
	refreshToken := body.RefreshToken

	// 如果当前时间大于过期时间的一半，则生成新令牌
	halfExp := exp.Add(-(exp.Sub(iat.Time)) / 2)
	if now.After(halfExp) {
		refreshToken, refreshExpiresIn = token.UserTokenCreate(userId, deviceFingerprint, "refresh")
	}

	// 当前请求信息
	ipaddr, location := reqctx.IPAddrLocation(c)
	os, browser := reqctx.UaOsBrowser(c)
	// 记录令牌，创建系统访问记录
	token.UserInfoCreate(&info, deviceFingerprint, [4]string{ipaddr, location, os, browser})
	s.accountService.UpdateLoginDateAndIP(info)
	s.sysLogLoginService.Insert(
		info.User.UserName, constants.STATUS_YES, "Refresh Access Token Successful",
		[4]string{ipaddr, location, os, browser},
	)

	// 返回访问令牌和刷新令牌
	c.JSON(200, resp.OkData(map[string]any{
		"tokenType":        constants.HEADER_PREFIX,
		"accessToken":      accessToken,
		"expiresIn":        expiresIn,
		"refreshToken":     refreshToken,
		"refreshExpiresIn": refreshExpiresIn,
		"userId":           userId,
	}))
}

// LoginSource 登录认证源
//
// GET /auth/login/source
func (s AccountController) LoginSource(c *gin.Context) {
	data := s.accountService.LoginSource()
	c.JSON(200, resp.OkData(data))
}
