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

package shop

import (
	"context"
	"errors"

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

// 获取店铺邀请列表
func NewListShopInvitationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListShopInvitationsLogic {
	return &ListShopInvitationsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

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

	shop, err := l.svcCtx.ShopRpc.GetShopsById(l.ctx, &pb.GetShopsByIdReq{Id: req.Id})
	if err != nil {
		return nil, err
	}
	if shop.Shops == nil {
		return nil, errors.New("shop not found")
	}
	if shop.Shops.OwnerId != userID {
		return nil, contextj.ERRILLEGALUSER
	}

	result, err := l.svcCtx.ShopRpc.SearchShopInvitations(l.ctx, &pb.SearchShopInvitationsReq{
		ShopId: req.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
}
