package utils

import (
	"go.mongodb.org/mongo-driver/bson"
	codeword_rpc "penahub.gitlab.yandexcloud.net/pena-services/customer/internal/proto/codeword"
	"time"
)

func MatchGen(codewordData map[string][]*codeword_rpc.PromoActivationResp_UserTime, from, to int64) bson.M {
	userActivations := make(map[string]int64)

	for _, values := range codewordData {
		for _, activation := range values {
			userActivations[activation.UserID] = activation.Time
		}
	}

	var conditions []bson.M
	for userID, activation := range userActivations {
		var condition bson.M
		if activation < from {
			condition = bson.M{"userId": userID, "createdAt": bson.M{"$gte": time.Unix(from, 0), "$lte": time.Unix(to, 0)}, "key": "payment.succeeded"}
		} else {
			condition = bson.M{"userId": userID, "createdAt": bson.M{"$gte": time.Unix(activation, 0), "$lte": time.Unix(to, 0)}, "key": "payment.succeeded"}
		}
		conditions = append(conditions, condition)
	}

	match := bson.M{
		"$match": bson.M{"$or": conditions},
	}

	return match
}
