package logic

import (
	"context"
	"errors"

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

	"entgo.io/ent/dialect/sql"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *SearchDisputeTimelineLogic) SearchDisputeTimeline(in *pb.SearchDisputeTimelineReq) (*pb.SearchDisputeTimelineResp, error) {
	limit := in.GetLimit()
	if limit <= 0 {
		limit = 20
	}
	if limit > 100 {
		return nil, errors.New("limit too large")
	}
	offset := in.GetOffset()
	if offset < 0 {
		offset = 0
	}

	query := l.svcCtx.DisputeModelRO.DisputeTimeline.Query()
	if in.DisputeId != nil {
		query = query.Where(disputetimeline.DisputeIDEQ(in.GetDisputeId()))
	}

	list, err := query.
		Order(disputetimeline.ByCreatedAt(sql.OrderAsc()), disputetimeline.ByID(sql.OrderAsc())).
		Offset(int(offset)).
		Limit(int(limit)).
		All(l.ctx)
	if err != nil {
		logx.Errorf("searchDisputeTimeline err: %v", err)
		return nil, errors.New("search dispute timeline failed")
	}

	out := make([]*pb.DisputeTimeline, len(list))
	for i, item := range list {
		out[i] = entDisputeTimelineToPb(item)
	}

	return &pb.SearchDisputeTimelineResp{Timeline: out}, nil
}
