package logic

import (
	"context"
	"errors"
	"juwan-backend/app/users/rpc/internal/models/users"
	"juwan-backend/app/users/rpc/internal/svc"
	utils2 "juwan-backend/app/users/rpc/internal/utils"
	"juwan-backend/app/users/rpc/pb"
	"juwan-backend/common/utils/pwdUtils"

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

//var UserNotFound = errors.New("user not Found")

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

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

func (l *LoginLogic) Login(in *pb.LoginReq) (*pb.LoginResp, error) {
	user, err := l.svcCtx.UsersModelRO.Users.Query().
		Where(users.UsernameEQ(in.Username)).
		Select(users.FieldID, users.FieldUsername, users.FieldPasswordHash, users.FieldEmail, users.FieldIsAdmin).
		First(l.ctx)
	if err != nil {
		logx.WithContext(l.ctx).Errorf("LoginLogic.Login error:%v", err)
		return nil, errors.New("user not found")
	}
	logx.Infof("user:%v", user)
	if !pwdUtils.VerifyPassword(user.PasswordHash, in.Passwd) {
		logx.WithContext(l.ctx).Errorf("User %s Login failed", user.Username)
		return nil, errors.New("incorrect password")
	}

	token, err := l.svcCtx.JwtManager.New(l.ctx, &utils2.TokenPayload{
		UserId:  user.ID,
		IsAdmin: user.IsAdmin,
	})
	if err != nil {
		logx.Errorf("LoginLogic.Login gen jwt for user %v error:%v", user.ID, err)
		return nil, err
	}

	return &pb.LoginResp{
		Token:    token,
		Username: user.Username,
		Email:    user.Email,
		Id:       user.ID,
	}, nil
}
