package User

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"github.com/zeromicro/go-zero/core/errorx"
	"time"
	"wechat-api/internal/utils"
	"wechat-api/internal/utils/jwt"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DoGptsUserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDoGptsUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DoGptsUserLoginLogic {
	return &DoGptsUserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *DoGptsUserLoginLogic) DoGptsUserLogin(req *types.GptsUserLoginReq) (resp *types.GptsUserLoginResp, err error) {
	user, err := l.svcCtx.CoreRpc.GetUserByUsername(l.ctx,
		&core.UsernameReq{
			Username: *req.Username,
		})

	if err != nil {
		l.Logger.Errorf("gpts user login err=%v\n", err)
		return nil, errorx.NewCodeInvalidArgumentError("用户名或密码错误")
	}
	if user == nil {
		l.Logger.Errorf("gpts user login user=%v\n", user)
		return nil, errorx.NewCodeInvalidArgumentError("用户名或密码错误")
	}

	if user.Status != nil && *user.Status != uint32(utils.StatusNormal) {
		return nil, errorx.NewCodeInvalidArgumentError("用户被锁定")
	}

	if !utils.BcryptCheck(*req.Password, *user.Password) {
		l.Logger.Errorf("gpts user login check password failed\n")
		return nil, errorx.NewCodeInvalidArgumentError("用户名或密码错误")
	}

	valid := utils.CheckGptLogin(user.RoleIds)
	if !valid {
		return nil, errorx.NewInvalidArgumentError("用户不允许登陆")
	}

	token, err := jwt.NewJwtToken(
		l.svcCtx.Config.Auth.AccessSecret,
		time.Now().Unix(),
		l.svcCtx.Config.Auth.AccessExpire,
		jwt.WithOption("userId", user.Id),
	)
	if err != nil {
		return nil, err
	}

	// add token into database
	expiredAt := time.Now().Add(time.Second * time.Duration(l.svcCtx.Config.Auth.AccessExpire)).UnixMilli()
	_, err = l.svcCtx.CoreRpc.CreateToken(l.ctx, &core.TokenInfo{
		Uuid:      user.Id,
		Token:     pointy.GetPointer(token),
		Source:    pointy.GetPointer("core_user"),
		Status:    pointy.GetPointer(uint32(utils.StatusNormal)),
		Username:  user.Username,
		ExpiredAt: pointy.GetPointer(expiredAt),
	})

	if err != nil {
		return nil, err
	}

	resp = &types.GptsUserLoginResp{
		BaseDataInfo: types.BaseDataInfo{Msg: errormsg.Success},
		Data: types.GptsUserToken{
			ID:         *user.Id,
			Token:      token,
			Username:   *user.Username,
			ExpireTime: uint64(expiredAt),
		},
	}
	return resp, nil
}
