// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1

package shop

import (
	"context"

	"juwan-backend/app/player/rpc/playerservice"
	"juwan-backend/app/shop/api/internal/svc"
	"juwan-backend/app/shop/api/internal/types"
	"juwan-backend/app/shop/rpc/pb"
	"juwan-backend/common/utils/contextj"

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

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

// 获取我收到的邀请
func NewMyInvitationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MyInvitationsLogic {
	return &MyInvitationsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MyInvitationsLogic) MyInvitations() (resp *types.ShopInvitationListResp, err error) {
	userID, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}

	playerResp, err := l.svcCtx.PlayerRpc.GetPlayerByUserId(l.ctx, &playerservice.SearchPlayersReq{UserId: &userID})
	if err != nil {
		return nil, err
	}
	player := playerResp.GetPlayers()
	if player == nil {
		return &types.ShopInvitationListResp{Items: []types.ShopInvitation{}}, nil
	}

	result, err := l.svcCtx.ShopRpc.SearchShopInvitations(l.ctx, &pb.SearchShopInvitationsReq{
		PlayerId: player.Id,
		Limit:    100,
	})
	if err != nil {
		return nil, err
	}

	items := make([]types.ShopInvitation, 0, len(result.ShopInvitations))
	for _, inv := range result.ShopInvitations {
		items = append(items, types.ShopInvitation{
			Id:          inv.Id,
			ShopId:      inv.ShopId,
			PlayerId:    inv.PlayerId,
			Status:      inv.Status,
			InvitedBy:   inv.InvitedBy,
			CreatedAt:   inv.CreatedAt,
			RespondedAt: inv.RespondedAt,
		})
	}

	return &types.ShopInvitationListResp{Items: items}, nil
}
