package staff

import (
	"context"
	"time"

	"bsm/full/module/ec/mall/internal/impl"
	"bsm/full/module/ec/mall/internal/models"
	"bsm/full/module/ec/mall/internal/password"
	pb "bsm/full/module/ec/mall/pb"

	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
)

// SetPassword sets the authenticated staff password.
func SetPassword(ctx context.Context, in *pb.SetAccountRequest) (reply *pb.IdentityStatusReply, err error) {
	auth, err := service.ParseMetaCtx(ctx, &service.ParseOptions{RoleValue: "Mall_Admin"})
	if err != nil {
		return nil, err
	}
	if in.Password == "" || in.Password != in.PasswordConfirmed {
		return nil, errcode.ErrInvalidArgument
	}

	passwordHash, err := password.Hash(in.Password)
	if err != nil {
		return nil, err
	}
	err = impl.DBService.Where("id = ?", auth.ID).Updates(&models.MallStaff{
		Salt:     "",
		Password: passwordHash,
	}).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	return &pb.IdentityStatusReply{
		Code:    0,
		Message: "OK",
		Timeseq: time.Now().UnixMilli(),
	}, nil
}
