package logic

import (
	"context"
	"errors"

	"juwan-backend/app/dispute/rpc/internal/models/disputes"
	"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 SearchDisputesLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *SearchDisputesLogic) SearchDisputes(in *pb.SearchDisputesReq) (*pb.SearchDisputesResp, 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.Disputes.Query()
	if in.Id != nil {
		query = query.Where(disputes.IDEQ(in.GetId()))
	}
	if in.OrderId != nil {
		query = query.Where(disputes.OrderIDEQ(in.GetOrderId()))
	}
	if in.InitiatorId != nil {
		query = query.Where(disputes.InitiatorIDEQ(in.GetInitiatorId()))
	}
	if in.RespondentId != nil {
		query = query.Where(disputes.RespondentIDEQ(in.GetRespondentId()))
	}
	if in.Status != nil {
		query = query.Where(disputes.StatusEQ(in.GetStatus()))
	}

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

	out := make([]*pb.Disputes, len(list))
	for i, d := range list {
		out[i] = entDisputeToPb(d)
	}

	return &pb.SearchDisputesResp{Disputes: out}, nil
}
