package agency

import (
	"context"
	"fmt"
	"log"
	"time"

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

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

// SetPassword updates an agency password.
func SetPassword(ctx context.Context, in *pb.SetPasswordRequest) (reply *pb.IdentityStatusReply, err error) {
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}
	identity := auth.Identity
	if in.GetIdentity() != "" {
		identity = in.GetIdentity()
	}
	if in.GetOldPassword() == "" || in.GetNewPassword() == "" {
		return nil, errcode.ErrInvalidArgument
	}

	var agency models.MarketAgency
	if err := impl.DBService.Where("identity = ?", identity).First(&agency).Error; err != nil {
		log.Println("get agency failed:", err)
		return nil, err
	}
	if !password.Verify(agency.Password, in.GetOldPassword()) {
		return nil, errcode.ErrPassword
	}

	newPassword, err := password.Hash(in.GetNewPassword())
	if err != nil {
		return nil, fmt.Errorf("hash password: %w", err)
	}
	if err := impl.DBService.Model(&agency).Updates(map[string]any{
		"password": newPassword,
		"salt":     "",
	}).Error; err != nil {
		log.Println("update password failed:", err)
		return nil, err
	}

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