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

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

// -----------------------disputes-----------------------
func (l *AddDisputesLogic) AddDisputes(in *pb.AddDisputesReq) (*pb.AddDisputesResp, error) {
	if in.GetOrderId() <= 0 {
		return nil, errors.New("orderId is required")
	}
	if in.GetInitiatorId() <= 0 {
		return nil, errors.New("initiatorId is required")
	}
	if in.GetRespondentId() <= 0 {
		return nil, errors.New("respondentId is required")
	}
	if in.GetReason() == "" {
		return nil, errors.New("reason is required")
	}

	status := in.GetStatus()
	if status == "" {
		status = "open"
	}

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

	created, err := l.svcCtx.DisputeModelRW.Disputes.Create().
		SetID(idResp.Id).
		SetOrderID(in.GetOrderId()).
		SetInitiatorID(in.GetInitiatorId()).
		SetInitiatorName(in.GetInitiatorName()).
		SetRespondentID(in.GetRespondentId()).
		SetReason(in.GetReason()).
		SetEvidence(toTextArray(in.GetEvidence())).
		SetStatus(status).
		Save(l.ctx)
	if err != nil {
		logx.Errorf("addDisputes err: %v", err)
		return nil, errors.New("add dispute failed")
	}

	return &pb.AddDisputesResp{Id: created.ID}, nil
}
