package schema

import (
	"context"
	"log"
	"os"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"database/sql"

	"github.com/uptrace/bun"

	"github.com/uptrace/bun/dialect/pgdialect"
	"github.com/uptrace/bun/driver/pgdriver"
)

func GetTestDatabase() (*bun.DB, error) {
	var err error

	dsn := "postgres://kontor:kontor@localhost:5432/kontor?sslmode=disable"
	sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn)))

	sqldb.SetMaxOpenConns(4)
	sqldb.SetMaxIdleConns(4)

	DB := bun.NewDB(sqldb, pgdialect.New())
	// DB.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true)))

	if err = DB.Ping(); err != nil {
		return nil, err
	}

	log.Println("Returned Database Connection")
	return DB, nil
}

func TestMain(m *testing.M) {
	log.Println("Setup Test")
	exitCode := m.Run()
	os.Exit(exitCode)
}

func TestSelectComics(t *testing.T) {
	var comics []Comic
	var err error
	var db *bun.DB
	ctx := context.Background()

	db, err = GetTestDatabase()
	require.NoError(t, err)

	err = db.NewSelect().Model(&comics).Relation("Publisher").Scan(ctx)
	if err != nil {
		log.Fatal(err)
	}

	require.NoError(t, err)
	assert.Equal(t, 168, len(comics))
}

func TestSelectPublishers(t *testing.T) {
	var publishers []Publisher
	var err error
	var db *bun.DB
	ctx := context.Background()

	db, err = GetTestDatabase()
	require.NoError(t, err)

	err = db.NewSelect().Model(&publishers).Relation("ParentPublisher").Scan(ctx)
	if err != nil {
		log.Fatal(err)
	}

	require.NoError(t, err)
	assert.Equal(t, 19, len(publishers))
}

func TestSelectWorkTypes(t *testing.T) {
	var comic_works []ComicWork
	var err error
	var db *bun.DB
	ctx := context.Background()

	db, err = GetTestDatabase()
	if err != nil {
		log.Fatal(err)
	}

	err = db.NewSelect().Model(&comic_works).Relation("Comic").Relation("Artist").Relation("WorkType").Scan(ctx)
	if err != nil {
		log.Fatal(err)
	}

	require.NoError(t, err)
	assert.Equal(t, 59, len(comic_works))
}
