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

package review

import (
	"context"
	"errors"

	"juwan-backend/app/order/rpc/orderservice"
	"juwan-backend/app/review/api/internal/svc"
	"juwan-backend/app/review/api/internal/types"
	reviewpb "juwan-backend/app/review/rpc/pb"
	"juwan-backend/common/utils/contextj"

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

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

// 获取订单评价
func NewGetOrderReviewsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOrderReviewsLogic {
	return &GetOrderReviewsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetOrderReviewsLogic) GetOrderReviews(req *types.GetOrderReviewsReq) (resp *types.ReviewListResp, err error) {
	uid, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	orderResp, err := l.svcCtx.OrderRpc.GetOrdersById(l.ctx, &orderservice.GetOrdersByIdReq{Id: req.Id})
	if err != nil {
		return nil, err
	}
	order := orderResp.GetOrders()
	consumerID, playerUserID, err := orderParticipantUserIDs(l.ctx, l.svcCtx, order)
	if err != nil {
		return nil, err
	}
	if uid != consumerID && uid != playerUserID {
		return nil, errors.New("not a participant of this order")
	}

	orderId := req.Id
	sealed := false
	result, err := l.svcCtx.ReviewRpc.SearchReviews(l.ctx, &reviewpb.SearchReviewsReq{
		Offset:  0,
		Limit:   10,
		OrderId: &orderId,
		Sealed:  &sealed,
	})
	if err != nil {
		return nil, err
	}

	items := make([]types.Review, 0, len(result.GetReviews()))
	for _, r := range result.GetReviews() {
		items = append(items, toAPIReview(r))
	}
	return &types.ReviewListResp{
		Items: items,
		Meta: types.PageMeta{
			Total:  int64(len(items)),
			Offset: 0,
			Limit:  10,
		},
	}, nil
}
