package service_test

import (
	"flag"
	"log"
	"os"
	"testing"

	"gitea.dwysokinski.me/twhelp/corev3/internal/bun/buntest"
	"gitea.dwysokinski.me/twhelp/corev3/internal/watermill/watermillamqptest"
	"github.com/ory/dockertest/v3"
)

var (
	postgres *buntest.Postgres
	rabbitMQ *watermillamqptest.RabbitMQ
)

func TestMain(m *testing.M) {
	os.Exit(testMainWrapper(m))
}

func testMainWrapper(m *testing.M) int {
	// https://github.com/golang/go/blob/7cfa7d69259590319524c3715df4a39b39924bc3/src/testing/testing.go#L224
	flag.Parse()

	if testing.Short() {
		return m.Run()
	}

	pool, err := dockertest.NewPool("")
	if err != nil {
		log.Println("couldn't construct dockertest.Pool:", err)
		return 1
	}

	postgres, err = buntest.NewPostgres(pool, buntest.WithPostgresTTL(180))
	if err != nil {
		log.Println("couldn't construct adaptertest.Postgres:", err)
		return 1
	}
	defer func() {
		_ = postgres.Close()
	}()

	rabbitMQ, err = watermillamqptest.NewRabbitMQ(pool, watermillamqptest.WithRabbitMQTTL(180))
	if err != nil {
		log.Println("couldn't construct watermillamqptest.RabbitMQ:", err)
		return 1
	}
	defer func() {
		_ = rabbitMQ.Close()
	}()

	return m.Run()
}
