package integration

import (
	"context"
	"fmt"
	"github.com/stretchr/testify/assert"
	"go.uber.org/zap"
	"log"
	"penahub.gitlab.yandexcloud.net/backend/penahub_common/mongo"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/interface/client"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/interface/repository"
	codeword_rpc "penahub.gitlab.yandexcloud.net/pena-services/customer/internal/proto/codeword"
	"testing"
	"time"
)

func Test_PromoLTV(t *testing.T) {
	logger, err := zap.NewProduction(zap.AddStacktrace(zap.DPanicLevel))
	if err != nil {
		log.Fatalf("failed to init zap logger: %v", err)
	}

	ctx := context.Background()

	codeword := client.NewCodewordClient(client.CodewordClientDeps{
		Logger:              logger,
		CodewordServiceHost: "localhost:9000",
	})

	mdb, err := mongo.Connect(ctx, &mongo.ConnectDeps{
		Configuration: &mongo.Configuration{
			Host:         "localhost",
			Port:         "27020",
			User:         "test",
			Password:     "test",
			Auth:         "admin",
			DatabaseName: "admin",
		},
		Timeout: 10 * time.Second,
	})

	from := int64(0)
	to := int64(1714291104)

	historyRepo := repository.NewHistoryRepository(repository.HistoryRepositoryDeps{
		Logger:  logger,
		MongoDB: mdb.Collection("histories"),
	})

	codewordData, err := codeword.GetAllPromoActivations(ctx, &codeword_rpc.Time{
		From: from,
		To:   to,
	})

	assert.NoError(t, err)

	userSumMap, err := historyRepo.GetPayUsersPromoHistory(ctx, codewordData, from, to)
	assert.NoError(t, err)

	fmt.Println("userSumMap", userSumMap)

	resp := make(map[string]struct {
		Regs  int
		Money int64
	})

	for promoID, data := range codewordData {
		for _, value := range data {

			paids, ok := userSumMap[value.UserID]
			if !ok {
				paids = 0
			}

			if value.Time >= from && value.Time <= to {
				if _, ok := resp[promoID]; !ok {
					resp[promoID] = struct {
						Regs  int
						Money int64
					}{Regs: 1, Money: paids}
					continue
				}
				current := resp[promoID]
				current.Regs += 1
				current.Money += paids
			}
		}
	}

	fmt.Println(resp)
}
