package logic

import (
	"context"
	"errors"
	"juwan-backend/app/game/rpc/internal/svc"
	"juwan-backend/app/game/rpc/pb"

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

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

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

func (l *SearchGamesLogic) SearchGames(in *pb.SearchGamesReq) (*pb.SearchGamesResp, 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
	}
	all, err := l.svcCtx.GameModelRO.Games.Query().Limit(int(in.Limit)).Offset(int(in.Offset)).All(l.ctx)
	if err != nil && !errors.Is(err, entcache.ErrNotFound) {
		logx.Errorf("failed to query games: %v", err)
		return nil, errors.New("failed to query games")
	}
	logx.Debugf("games: %v", all)
	if err != nil {
		return &pb.SearchGamesResp{}, nil
	}
	list := make([]*pb.Games, 0, len(all))
	for _, v := range all {
		temp := &pb.Games{}
		err := copier.Copy(temp, v)
		if err != nil {
			logx.Errorf("failed to copy games: %v", err)
			return nil, errors.New("failed to copy games")
		}
		temp.CreatedAt = v.CreatedAt.Unix()
		temp.UpdatedAt = v.UpdatedAt.Unix()
		list = append(list, temp)
	}
	return &pb.SearchGamesResp{
		Games: list,
	}, nil
}
