package logic

import (
	"context"
	"errors"
	"juwan-backend/app/game/rpc/internal/models/games"
	"juwan-backend/app/snowflake/rpc/snowflake"

	"juwan-backend/app/game/rpc/internal/svc"
	"juwan-backend/app/game/rpc/pb"

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

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

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

// -----------------------games-----------------------
func (l *AddGamesLogic) AddGames(in *pb.AddGamesReq) (*pb.AddGamesResp, error) {
	idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{})
	if err != nil {
		logx.Errorf("AddGamesLogic.addGames err:%v", err)
		return nil, errors.New("create game id failed")
	}
	_, err = l.svcCtx.GameModelRW.Games.Create().
		SetID(idResp.Id).
		SetName(in.Name).
		SetIcon(in.Icon).
		SetCategory(in.Category).
		SetSortOrder(0).
		Save(l.ctx)
	if err != nil {
		logx.Errorf("AddGamesLogic.addGames err:%v", err)
		return nil, errors.New("add game failed")
	}

	game, err := l.svcCtx.GameModelRO.Games.Query().Where(games.IDEQ(idResp.Id)).First(l.ctx)
	if err != nil {
		logx.Errorf("AddGamesLogic.getGamesById err:%v", err)
		return nil, errors.New("get game failed")
	}

	pbGame := pb.Games{}
	err = copier.Copy(&pbGame, &game)
	if err != nil {
		logx.Errorf("AddGamesLogic.copier err:%v", err)
		return nil, errors.New("get game failed")
	}
	pbGame.CreatedAt = game.CreatedAt.Unix()
	pbGame.UpdatedAt = game.UpdatedAt.Unix()

	return &pb.AddGamesResp{Games: &pbGame}, nil
}
