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

package shop

import (
	"context"

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

	"juwan-backend/app/shop/api/internal/svc"
	"juwan-backend/app/shop/api/internal/types"

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

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

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

func (l *ListShopsLogic) ListShops(req *types.PageReq) (resp *types.ShopListResp, err error) {
	if req.Limit <= 0 {
		req.Limit = 20
	}

	result, err := l.svcCtx.ShopRpc.SearchShops(l.ctx, &pb.SearchShopsReq{
		Offset: req.Offset,
		Limit:  req.Limit,
	})
	if err != nil {
		return nil, err
	}

	items := make([]types.ShopProfile, 0, len(result.Shops))
	for _, item := range result.Shops {
		profile := toShopProfile(item)
		if profile != nil {
			items = append(items, *profile)
		}
	}

	return &types.ShopListResp{
		Items: items,
		Meta: types.PageMeta{
			Total:  int64(len(items)),
			Offset: req.Offset,
			Limit:  req.Limit,
		},
	}, nil

}
