package logic

import (
	"context"
	"errors"
	"juwan-backend/app/user_verifications/rpc/internal/models"
	"juwan-backend/app/user_verifications/rpc/internal/models/predicate"
	"juwan-backend/app/user_verifications/rpc/internal/models/userverifications"
	"juwan-backend/app/user_verifications/rpc/internal/svc"
	"juwan-backend/app/user_verifications/rpc/pb"

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

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

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

func (l *SearchUserVerificationsLogic) SearchUserVerifications(in *pb.SearchUserVerificationsReq) (*pb.SearchUserVerificationsResp, error) {
	if in.Limit <= 0 {
		in.Limit = 20
	}
	if in.Limit > 100 {
		return nil, errors.New("limit too large")
	}
	if in.Offset < 0 {
		in.Offset = 0
	}
	predicates := make([]predicate.UserVerifications, 0, 3)
	if in.UserId != 0 {
		predicates = append(predicates, userverifications.UserIDEQ(in.UserId))
	}
	if in.Role != "" {
		predicates = append(predicates, userverifications.RoleEQ(in.Role))
	}
	if in.Status != "" {
		predicates = append(predicates, userverifications.StatusEQ(in.Status))
	}

	verifications, err := l.svcCtx.UserVeriModelRO.Query().Where(predicates...).
		Offset(int(in.Offset)).
		Limit(int(in.Limit)).
		All(l.ctx)
	if err != nil {
		logx.Errorf("Get all verifications err: %s", err.Error())
		return nil, errors.New("get all verifications err")
	}
	return &pb.SearchUserVerificationsResp{
		UserVerifications: convertModelUserVerificationsToProto(verifications),
	}, nil
}

func convertModelUserVerificationToProto(modelUserVerification *models.UserVerifications) *pb.UserVerifications {

	if modelUserVerification == nil {
		return nil
	}
	out := &pb.UserVerifications{}
	err := copier.Copy(out, modelUserVerification)
	if err != nil {
		logx.Errorf("copy modelUserVerification err: %s", err.Error())
		return out
	}

	out.CreatedAt = modelUserVerification.CreatedAt.Unix()
	out.UpdatedAt = modelUserVerification.UpdatedAt.Unix()
	return out
}

func convertModelUserVerificationsToProto(modelUserVerifications []*models.UserVerifications) []*pb.UserVerifications {

	out := make([]*pb.UserVerifications, 0, len(modelUserVerifications))
	for _, modelUserVerification := range modelUserVerifications {
		out = append(out, convertModelUserVerificationToProto(modelUserVerification))
	}

	return out
}
