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

package dispute

import (
	"context"
	"errors"
	"time"

	"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 AppealDisputeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 申诉
func NewAppealDisputeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AppealDisputeLogic {
	return &AppealDisputeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AppealDisputeLogic) AppealDispute(req *types.AppealReq) (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.GetInitiatorId() && uid != d.GetRespondentId() {
		return nil, errors.New("not a participant of this dispute")
	}
	if d.GetStatus() != "resolved" {
		return nil, errors.New("dispute status does not allow appeal")
	}

	status := "appealed"
	now := time.Now().Unix()
	_, err = l.svcCtx.DisputeRpc.UpdateDisputes(l.ctx, &disputeservice.UpdateDisputesReq{
		Id:           req.Id,
		Status:       &status,
		AppealReason: &req.Reason,
		AppealedAt:   &now,
	})
	if err != nil {
		return nil, err
	}

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

	return &types.EmptyResp{}, nil
}
