package logic

import (
	"context"
	"errors"
	"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 ListUserVerificationsByUserIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *ListUserVerificationsByUserIdLogic) ListUserVerificationsByUserId(in *pb.ListUserVerificationsByUserIdReq) (*pb.ListUserVerificationsByUserIdResp, error) {
	all, err := l.svcCtx.UserVeriModelRO.Query().
		Where(userverifications.UserIDEQ(in.UserId)).
		All(l.ctx)

	if err != nil {
		logx.Errorf("ListUserVerificationsByUserId err: %v", err)
		return nil, errors.New("list user verifications by user id err")
	}

	list := make([]*pb.UserVerifications, 0, len(all))
	for _, v := range all {
		var temp pb.UserVerifications
		err = copier.Copy(&temp, v)
		if err != nil {
			logx.Errorf("copy user verifications err: %v", err)
			continue
		}
		temp.CreatedAt = v.CreatedAt.Unix()
		temp.UpdatedAt = v.UpdatedAt.Unix()
		if v.ReviewedAt != nil {
			temp.ReviewedAt = v.ReviewedAt.Unix()
		}
		list = append(list, &temp)
	}

	return &pb.ListUserVerificationsByUserIdResp{
		UserVerifications: list,
	}, nil
}
