package admin_auth

import (
	"context"

	"znc-server/app/main/api/internal/svc"
	"znc-server/app/main/api/internal/types"
	"znc-server/app/main/model"
	jwtx "znc-server/common/jwt"
	"znc-server/common/xerr"
	"znc-server/pkg/lzkit/crypto"

	"github.com/Masterminds/squirrel"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *AdminLoginLogic) AdminLogin(req *types.AdminLoginReq) (resp *types.AdminLoginResp, err error) {
	// 1. 验证验证码
	if !req.Captcha {
		return nil, errors.Wrapf(xerr.NewErrMsg("验证码错误"), "用户登录, 验证码错误, 验证码: %v", req.Captcha)
	}

	// 2. 验证用户名和密码
	user, err := l.svcCtx.AdminUserModel.FindOneByUsername(l.ctx, req.Username)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("用户名或密码错误"), "用户登录, 用户名或密码错误, 用户名: %s", req.Username)
	}

	// 3. 验证密码
	if !crypto.PasswordVerify(req.Password, user.Password) {
		return nil, errors.Wrapf(xerr.NewErrMsg("用户名或密码错误"), "用户登录, 用户名或密码错误, 用户名: %s", req.Username)
	}

	// 4. 获取权限
	adminUserRoleBuilder := l.svcCtx.AdminUserRoleModel.SelectBuilder().Where(squirrel.Eq{"user_id": user.Id})
	permissions, err := l.svcCtx.AdminUserRoleModel.FindAll(l.ctx, adminUserRoleBuilder, "role_id DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("获取权限失败"), "用户登录, 获取权限失败, 用户名: %s", req.Username)
	}

	// 获取角色ID数组
	roleIds := make([]int64, 0)
	for _, permission := range permissions {
		roleIds = append(roleIds, permission.RoleId)
	}

	// 获取角色名称
	roles := make([]string, 0)
	for _, roleId := range roleIds {
		role, err := l.svcCtx.AdminRoleModel.FindOne(l.ctx, roleId)
		if err != nil {
			continue
		}
		roles = append(roles, role.RoleCode)
	}

	// 5. 生成token
	refreshToken := l.svcCtx.Config.JwtAuth.RefreshAfter
	expiresAt := l.svcCtx.Config.JwtAuth.AccessExpire
	claims := jwtx.JwtClaims{
		UserId:   user.Id,
		AgentId:  0,
		Platform: model.PlatformAdmin,
		UserType: model.UserTypeAdmin,
		IsAgent:  model.AgentStatusNo,
	}
	token, err := jwtx.GenerateJwtToken(claims, l.svcCtx.Config.JwtAuth.AccessSecret, expiresAt)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("生成token失败"), "用户登录, 生成token失败, 用户名: %s", req.Username)
	}

	return &types.AdminLoginResp{
		AccessToken:  token,
		AccessExpire: expiresAt,
		RefreshAfter: refreshToken,
		Roles:        roles,
	}, nil
}
