package logic

import (
	"context"
	"time"

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

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

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

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

func (l *UpdateDisputesLogic) UpdateDisputes(in *pb.UpdateDisputesReq) (*pb.UpdateDisputesResp, error) {
	updater := l.svcCtx.DisputeModelRW.Disputes.UpdateOneID(in.GetId())

	if in.Status != nil {
		updater = updater.SetStatus(in.GetStatus())
	}
	if in.Result != nil {
		updater = updater.SetResult(in.GetResult())
	}
	if in.RespondentReason != nil {
		updater = updater.SetRespondentReason(in.GetRespondentReason())
	}
	if len(in.GetRespondentEvidence()) > 0 {
		updater = updater.SetRespondentEvidence(toTextArray(in.GetRespondentEvidence()))
	}
	if in.AppealReason != nil {
		updater = updater.SetAppealReason(in.GetAppealReason())
	}
	if in.AppealedAt != nil {
		updater = updater.SetAppealedAt(time.Unix(in.GetAppealedAt(), 0))
	}
	if in.ResolvedBy != nil {
		updater = updater.SetResolvedBy(in.GetResolvedBy())
	}
	if in.ResolvedAt != nil {
		updater = updater.SetResolvedAt(time.Unix(in.GetResolvedAt(), 0))
	}

	_, err := updater.Save(l.ctx)
	if err != nil {
		logx.Errorf("updateDisputes err: %v", err)
		return nil, err
	}

	return &pb.UpdateDisputesResp{}, nil
}
