package logic

import (
	"context"
	"errors"
	"juwan-backend/app/shop/rpc/internal/models/shopplayers"

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

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

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

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

func (l *GetShopPlayersByIdLogic) GetShopPlayersById(in *pb.GetShopPlayersByIdReq) (*pb.GetShopPlayersByIdResp, error) {
	shopPlayer, err := l.svcCtx.ShopModelRO.ShopPlayers.Query().Where(
		shopplayers.ShopIDEQ(in.ShopId),
		shopplayers.PlayerIDEQ(in.PlayerId),
	).First(l.ctx)
	if err != nil {
		logx.WithContext(l.ctx).Errorf("GetShopPlayersByIdLogic err: %v", err)
		return nil, errors.New("get shop players by id failed")
	}

	pbShopPlayer := pb.ShopPlayers{
		ShopId:    shopPlayer.ShopID,
		PlayerId:  shopPlayer.PlayerID,
		IsPrimary: shopPlayer.IsPrimary,
		JoinedAt:  shopPlayer.JoinedAt.Unix(),
	}
	if shopPlayer.LeftAt != nil {
		pbShopPlayer.LeftAt = shopPlayer.LeftAt.Unix()
	}

	return &pb.GetShopPlayersByIdResp{ShopPlayers: &pbShopPlayer}, nil
}
