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

package dispute

import (
	"context"
	"errors"

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

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

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

// 获取订单争议
func NewGetOrderDisputeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOrderDisputeLogic {
	return &GetOrderDisputeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetOrderDisputeLogic) GetOrderDispute(req *types.DisputePathId) (resp *types.Dispute, 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()
	if order == nil {
		return nil, errors.New("order not found")
	}
	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")
	}

	out, err := l.svcCtx.DisputeRpc.SearchDisputes(l.ctx, &disputeservice.SearchDisputesReq{
		Offset:  0,
		Limit:   1,
		OrderId: &req.Id,
	})
	if err != nil {
		return nil, err
	}
	if len(out.GetDisputes()) == 0 {
		return nil, errors.New("dispute not found")
	}
	dispute := toAPIDispute(out.GetDisputes()[0])

	return &dispute, nil
}
