package controller

import (
	"fmt"

	"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/modules/auth/model"

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

// SMTP SMTP认证登录
//
// POST /auth/smtp
//
//	@Tags			common/authorization
//	@Accept			json
//	@Produce		json
//	@Param			data	body		object	true	"Request Param"
//	@Success		200		{object}	object	"Response Results"
//	@Summary		System Login
//	@Description	System Login
//	@Router			/auth/smtp [post]
func (s AccountController) SMTP(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var body model.LoginSourceBody
	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
	}

	// 当前请求信息
	ipaddr, location := reqctx.IPAddrLocation(c)
	os, browser := reqctx.UaOsBrowser(c)

	// 登录用户信息
	info, err := s.accountService.BySMTP(body)
	if err != nil {
		s.sysLogLoginService.Insert(
			body.Username, constants.STATUS_NO, err.Error(),
			[4]string{ipaddr, location, os, browser},
		)
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
		return
	}

	data := map[string]any{}

	deviceFingerprint := reqctx.DeviceFingerprint(c, info.UserId)

	// 生成访问令牌
	accessToken, expiresIn := token.UserTokenCreate(info.UserId, deviceFingerprint, "access")
	if accessToken == "" || expiresIn == 0 {
		c.JSON(200, resp.ErrMsg("token generation failed"))
		return
	}
	// 生成刷新令牌
	refreshToken, refreshExpiresIn := token.UserTokenCreate(info.UserId, deviceFingerprint, "refresh")

	// 记录令牌，创建系统访问记录
	token.UserInfoCreate(&info, deviceFingerprint, [4]string{ipaddr, location, os, browser})
	s.accountService.UpdateLoginDateAndIP(info)
	s.sysLogLoginService.Insert(
		body.Username, constants.STATUS_YES, "app.common.loginSuccess",
		[4]string{ipaddr, location, os, browser},
	)

	data["tokenType"] = constants.HEADER_PREFIX
	data["accessToken"] = accessToken
	data["expiresIn"] = expiresIn
	data["refreshToken"] = refreshToken
	data["refreshExpiresIn"] = refreshExpiresIn
	data["userId"] = info.UserId
	c.JSON(200, resp.OkData(data))
}
