package logic

import (
	"context"
	"errors"

	"juwan-backend/app/dispute/rpc/internal/svc"
	"juwan-backend/app/dispute/rpc/pb"
	"juwan-backend/app/snowflake/rpc/snowflake"

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

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

func NewAddDisputeTimelineLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddDisputeTimelineLogic {
	return &AddDisputeTimelineLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// -----------------------disputeTimeline-----------------------
func (l *AddDisputeTimelineLogic) AddDisputeTimeline(in *pb.AddDisputeTimelineReq) (*pb.AddDisputeTimelineResp, error) {
	if in.GetDisputeId() <= 0 {
		return nil, errors.New("disputeId is required")
	}
	if in.GetEventType() == "" {
		return nil, errors.New("eventType is required")
	}

	details, err := parseJSONMap(in.GetDetails())
	if err != nil {
		return nil, err
	}
	idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{})
	if err != nil {
		return nil, errors.New("create dispute timeline id failed")
	}

	_, err = l.svcCtx.DisputeModelRW.DisputeTimeline.Create().
		SetID(idResp.Id).
		SetDisputeID(in.GetDisputeId()).
		SetEventType(in.GetEventType()).
		SetActorID(in.GetActorId()).
		SetActorName(in.GetActorName()).
		SetDetails(details).
		Save(l.ctx)
	if err != nil {
		logx.Errorf("addDisputeTimeline err: %v", err)
		return nil, errors.New("add dispute timeline failed")
	}

	return &pb.AddDisputeTimelineResp{}, nil
}
