package auth

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/dal/errx"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/types/core"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/msg"
	"git.noahlan.cn/noahlan/ntool/ncrypt"
	"git.noahlan.cn/noahlan/ntool/nstr"

	"git.noahlan.cn/n-admin/n-admin-server/api/internal/svc"
	"git.noahlan.cn/n-admin/n-admin-server/api/internal/types"

	"net/http"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewLoginLogic(r *http.Request, ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		r:      r,
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	if err := l.svcCtx.Captcha.Verify(req.CaptchaId, req.Captcha, true); err != nil {
		return nil, err
	}
	var phone, email, username string
	if nstr.IsChineseMobile(req.Subject) {
		phone = req.Subject
	} else if nstr.IsEmail(req.Subject) {
		email = req.Subject
	} else {
		username = req.Subject
	}
	user, err := l.svcCtx.CoreRpc.GetUser(l.ctx, &core.UserReq{
		Username:    username,
		PhoneNumber: phone,
		Email:       email,
	})
	if err != nil {
		nerr := nstatus.ConvertErr(err)
		if nerr.Msg == msg.ObjectNotFound {
			return nil, nstatus.NewBizErrWithCode(errx.UserNotFound)
		}
		return nil, err
	}
	if !ncrypt.BcryptCheck(req.Credentials, user.Password) {
		return nil, nstatus.NewBizErrWithCode(errx.WrongPassword)
	}
	// 登录
	resp, err = login(l.ctx, l.svcCtx, l.r, user)
	if err != nil {
		return nil, err
	}
	return
}
