package account

import (
	"context"
	"time"

	"bsm/full/module/base/passport/internal/impl"
	"bsm/full/module/base/passport/internal/models"
	pb "bsm/full/module/base/passport/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
	"golang.org/x/crypto/bcrypt"
)

// 更新会员的密码
func SetPassword(ctx context.Context, in *pb.SetPasswordRequest) (reply *pb.StatusReply, err error) {
	if in.OldPassword == "" || in.NewPassword == "" {
		return nil, errcode.ErrInvalidArgument
	}
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}
	pa, err := models.GetPassportAccountByField("id", auth.ID)
	if err != nil {
		return nil, err
	}

	err = bcrypt.CompareHashAndPassword([]byte(pa.Password), []byte(in.OldPassword+pa.Salt))
	if err != nil {
		return nil, errcode.NewError(187, "Passport Error")
	}

	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(in.NewPassword+pa.Salt), bcrypt.MinCost)
	if err != nil {
		return nil, errcode.ErrInternal
	}

	err = impl.DBService.Model(&models.PassportAccount{}).Where("id = ? ", auth.ID).Update("password", string(hashedPassword)).Error
	if err != nil {
		printer.Error("Update passport account password by id %+v error:%v", auth.ID, err)
		return nil, errcode.ErrDB
	}

	return &pb.StatusReply{
		Timeseq: time.Now().UnixMilli(),
	}, nil

}
