package integration

import (
	"context"
	"database/sql"
	"github.com/stretchr/testify/assert"
	"github.com/themakers/hlog"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"log"
	"os"
	"penahub.gitlab.yandexcloud.net/external/trashlog/app"
	"penahub.gitlab.yandexcloud.net/external/trashlog/wrappers/zaptrashlog"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/models"
	"testing"
	"time"
)

var (
	commit    string = os.Getenv("COMMIT")
	buildTime string = os.Getenv("BUILD_TIME")
	version   string = os.Getenv("VERSION")
)

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

	ptime := time.Now()

	config := models.Config{
		Service: models.ServiceConfiguration{
			TrashLogHost: "localhost:7113",
		},
	}

	ctx := context.Background()

	clickHouseLogger, err := zaptrashlog.NewCore(ctx, zap.InfoLevel, config.Service.TrashLogHost, version, commit, ptime.Unix())
	if err != nil {
		panic(err)
	}

	loggerForHlog := logger.WithOptions(zap.WrapCore(func(core zapcore.Core) zapcore.Core {
		return zapcore.NewTee(core, clickHouseLogger)
	}))

	loggerHlog := hlog.New(loggerForHlog).Module("customer_test")
	loggerHlog.Emit(app.InfoSvcStarted{})

	clientClickHouse, err := sql.Open(
		"clickhouse",
		"tcp://127.0.0.1:9000?debug=true",
	)
	assert.NoError(t, err)

	time.Sleep(10 * time.Second)

	rows, err := clientClickHouse.Query("SELECT svc_commit, svc_build_time, svc_version FROM statistics")
	assert.NoError(t, err)

	defer rows.Close()
	foundCommit := false

	foundVersion := false
	for rows.Next() {
		var commitValue, buildTimeValue, versionValue string
		err := rows.Scan(&commitValue, &buildTimeValue, &versionValue)
		assert.NoError(t, err)
		if commitValue == commit {
			foundCommit = true
		}
		if versionValue == version {
			foundVersion = true
		}
	}

	assert.Equal(t, foundCommit, true, "commit value do not match")
	//assert.Equal(t, foundBuildTime, true, "buildTime value do not match")
	assert.Equal(t, foundVersion, true, "version value do not match")

}
