package admin

import (
	"context"
	"fmt"
	"time"

	"bindbox-game/configs"
	"bindbox-game/internal/pkg/jwtoken"
	"bindbox-game/internal/pkg/utils"
	"bindbox-game/internal/proposal"

	"gorm.io/gorm"
)

type LoginInput struct {
	Username string
	Password string
	IP       string
}

type LoginResult struct {
	Token   string
	IsSuper int32
}

func (s *service) Login(ctx context.Context, in LoginInput) (LoginResult, error) {
	info, err := s.readDB.Admin.WithContext(ctx).Where(s.readDB.Admin.Username.Eq(in.Username)).First()
	if err != nil && err != gorm.ErrRecordNotFound {
		return LoginResult{}, err
	}
	if err == gorm.ErrRecordNotFound {
		return LoginResult{}, fmt.Errorf("账号不存在，请联系管理员。")
	}
	if info.LoginStatus != 1 {
		return LoginResult{}, fmt.Errorf("账号已被禁用")
	}
	if !utils.VerifyAdminHashedPassword(info.Password, in.Password) {
		return LoginResult{}, fmt.Errorf("用户名或密码错误，请联系管理员。")
	}

	sessionUserInfo := proposal.SessionUserInfo{
		Id:       info.ID,
		UserName: info.Username,
		NickName: info.Nickname,
		IsSuper:  info.IsSuper,
		Platform: "管理端",
	}

	tokenString, err := jwtoken.New(configs.Get().JWT.AdminSecret).Sign(sessionUserInfo, 3*24*time.Hour)
	if err != nil {
		return LoginResult{}, fmt.Errorf("token 生成失败(%s)", err.Error())
	}

	info.LastLoginTime = time.Now()
	info.LastLoginIP = in.IP
	info.LastLoginHash = utils.MD5(tokenString)
	if err := s.writeDB.Admin.WithContext(ctx).Save(info); err != nil {
		return LoginResult{}, err
	}

	return LoginResult{Token: tokenString, IsSuper: info.IsSuper}, nil
}
