package buntest

import (
	"database/sql"

	"github.com/stretchr/testify/require"
	"github.com/uptrace/bun"
	"github.com/uptrace/bun/dialect/sqlitedialect"
	"github.com/uptrace/bun/driver/sqliteshim"
)

// NewSQLiteDB initializes a new instance of *bun.DB, which is ready for use (all required migrations are applied).
// Data is stored in memory (https://www.sqlite.org/inmemorydb.html).
func NewSQLiteDB(tb TestingTB) *bun.DB {
	tb.Helper()

	sqlDB, err := sql.Open(sqliteshim.ShimName, "file::memory:")
	require.NoError(tb, err)
	sqlDB.SetMaxOpenConns(1)
	sqlDB.SetMaxIdleConns(1)
	sqlDB.SetConnMaxLifetime(0)

	bunDB := bun.NewDB(sqlDB, sqlitedialect.New())
	tb.Cleanup(func() {
		_ = bunDB.Close()
	})

	bunDB.AddQueryHook(newBunDebugHook())

	runMigrations(tb, bunDB)

	return bunDB
}
