package logic

import (
	"context"
	"errors"
	"time"

	"juwan-backend/app/order/rpc/internal/models/orderstatelogs"
	"juwan-backend/app/order/rpc/internal/models/predicate"
	"juwan-backend/app/order/rpc/internal/svc"
	"juwan-backend/app/order/rpc/pb"

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

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

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

func (l *SearchOrderStateLogsLogic) SearchOrderStateLogs(in *pb.SearchOrderStateLogsReq) (*pb.SearchOrderStateLogsResp, error) {
	if in.Limit <= 0 {
		in.Limit = 20
	}
	if in.Limit > 100 {
		return nil, errors.New("limit too large")
	}
	if in.Offset < 0 {
		in.Offset = 0
	}

	preds := make([]predicate.OrderStateLogs, 0, 8)
	if in.Id != nil {
		preds = append(preds, orderstatelogs.IDEQ(*in.Id))
	}
	if in.OrderId != nil {
		preds = append(preds, orderstatelogs.OrderIDEQ(*in.OrderId))
	}
	if in.FromStatus != nil && *in.FromStatus != "" {
		preds = append(preds, orderstatelogs.FromStatusEQ(*in.FromStatus))
	}
	if in.ToStatus != nil && *in.ToStatus != "" {
		preds = append(preds, orderstatelogs.ToStatusEQ(*in.ToStatus))
	}
	if in.Action != nil && *in.Action != "" {
		preds = append(preds, orderstatelogs.ActionContainsFold(*in.Action))
	}
	if in.ActorId != nil {
		preds = append(preds, orderstatelogs.ActorIDEQ(*in.ActorId))
	}
	if in.ActorRole != nil && *in.ActorRole != "" {
		preds = append(preds, orderstatelogs.ActorRoleContainsFold(*in.ActorRole))
	}
	if in.CreatedAt != nil && *in.CreatedAt > 0 {
		preds = append(preds, orderstatelogs.CreatedAtGTE(time.Unix(*in.CreatedAt, 0)))
	}

	query := l.svcCtx.OrderModelsRO.OrderStateLogs.Query()
	if len(preds) > 0 {
		query = query.Where(orderstatelogs.And(preds...))
	}

	items, err := query.Offset(int(in.Offset)).Limit(int(in.Limit)).All(l.ctx)
	if err != nil {
		return nil, err
	}

	result := make([]*pb.OrderStateLogs, 0, len(items))
	for _, item := range items {
		result = append(result, toPBOrderStateLog(item))
	}

	return &pb.SearchOrderStateLogsResp{OrderStateLogs: result}, nil
}
