// 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/common/utils/contextj"

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

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

// 回应争议
func NewRespondDisputeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RespondDisputeLogic {
	return &RespondDisputeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RespondDisputeLogic) RespondDispute(req *types.DisputeResponseReq) (resp *types.EmptyResp, err error) {
	uid, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	if req.Reason == "" {
		return nil, errors.New("reason is required")
	}

	disputeResp, err := l.svcCtx.DisputeRpc.GetDisputesById(l.ctx, &disputeservice.GetDisputesByIdReq{Id: req.Id})
	if err != nil {
		return nil, err
	}
	d := disputeResp.GetDisputes()
	if d == nil {
		return nil, errors.New("dispute not found")
	}
	if uid != d.GetRespondentId() {
		return nil, errors.New("not the respondent of this dispute")
	}
	if d.GetStatus() != "open" {
		return nil, errors.New("dispute status does not allow response")
	}

	status := "reviewing"
	_, err = l.svcCtx.DisputeRpc.UpdateDisputes(l.ctx, &disputeservice.UpdateDisputesReq{
		Id:                 req.Id,
		Status:             &status,
		RespondentReason:   &req.Reason,
		RespondentEvidence: req.Evidence,
	})
	if err != nil {
		return nil, err
	}

	_, err = l.svcCtx.DisputeRpc.AddDisputeTimeline(l.ctx, &disputeservice.AddDisputeTimelineReq{
		DisputeId: req.Id,
		EventType: "response",
		ActorId:   uid,
		ActorName: actorName(uid),
		Details:   detailsJSON(map[string]any{"reason": req.Reason, "evidence": req.Evidence}),
	})
	if err != nil {
		return nil, err
	}

	return &types.EmptyResp{}, nil
}
