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

package dispute

import (
	"context"

	"juwan-backend/app/dispute/api/internal/svc"
	"juwan-backend/app/dispute/api/internal/types"
	"juwan-backend/app/dispute/rpc/disputeservice"
	"juwan-backend/common/utils/contextj"

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

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

// 获取争议列表
func NewListDisputesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListDisputesLogic {
	return &ListDisputesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListDisputesLogic) ListDisputes(req *types.DisputeListReq) (resp *types.DisputeListResp, err error) {
	uid, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	limit := req.Limit
	if limit <= 0 {
		limit = 20
	}
	var status *string
	if req.Status != "" {
		status = &req.Status
	}

	initiated, err := l.svcCtx.DisputeRpc.SearchDisputes(l.ctx, &disputeservice.SearchDisputesReq{
		Offset:      0,
		Limit:       100,
		InitiatorId: &uid,
		Status:      status,
	})
	if err != nil {
		return nil, err
	}
	responded, err := l.svcCtx.DisputeRpc.SearchDisputes(l.ctx, &disputeservice.SearchDisputesReq{
		Offset:       0,
		Limit:        100,
		RespondentId: &uid,
		Status:       status,
	})
	if err != nil {
		return nil, err
	}

	items := mergeDisputes(initiated.GetDisputes(), responded.GetDisputes())
	page := paginateDisputes(items, req.Offset, limit)
	out := make([]types.Dispute, 0, len(page))
	for _, item := range page {
		out = append(out, toAPIDispute(item))
	}

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