package account

import (
	"errors"
	"mtp20access/global"
	"mtp20access/model/account/request"
	accountRsp "mtp20access/model/account/response"
	commonRequest "mtp20access/model/common/request"
	"mtp20access/model/common/response"
	accountService "mtp20access/service/account"
	"mtp20access/utils"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// Login 账户登录
// @Summary 账户登录
// @accept   application/json
// @Produce  application/json
// @Param   data body     request.LoginReq                                       true "登录入参"
// @Success 200  {object} response.Response{data=accountRsp.LoginRsp,msg=string} "返回包括用户信息,token,过期时间"
// @Router  /Account/Login [post]
// @Tags     账户服务
func Login(c *gin.Context) {
	g := utils.GinUtils{C: c}
	r := request.LoginReq{}
	g.BindJsonReq(&r)

	if loginaccount, token, _, expiresAt, err := accountService.Login(r, g.C.ClientIP()); err == nil {
		response.OkWithDetailed(accountRsp.LoginRsp{
			LoginID:   int(loginaccount.LOGINID),
			UserID:    int(loginaccount.USERID),
			Token:     token,
			ExpiresAt: expiresAt,
		}, "登录成功", g.C)
	} else {
		global.M2A_LOG.Error(err.Error(), zap.Error(err))
		response.FailWithMessage(err.Error(), c)
	}
}

// TokenCheck Token校验
// @Summary  Token校验
// @Security ApiKeyAuth
// @accept  application/json
// @Produce application/json
// @Success  200 {object} response.Response{msg=string} "操作成功"
// @Router   /Account/TokenCheck [get]
// @Tags    账户服务
func TokenCheck(c *gin.Context) {
	// 获取请求账号信息
	s, exists := c.Get("claims")
	if !exists {
		err := errors.New("获取请求账号信息异常")
		response.FailWithMessage(err.Error(), c)
		return
	}
	claims := s.(*commonRequest.CustomClaims)

	token := c.Request.Header.Get("x-token")
	if err := accountService.RestoreLoginWithToken(claims.LoginID, claims.Group, token); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.Ok(c)
}

// Loginout 用户登出请求
// @Summary  用户登出请求
// @Security ApiKeyAuth
// @accept   application/json
// @Produce  application/json
// @Success  200 {object} response.Response{msg=string} "出参"
// @Router   /Account/Loginout [get]
// @Tags     账户服务
func Loginout(c *gin.Context) {
	if err := accountService.Logout(c); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithMessage("登出成功", c)
}
