package payment

import (
	"fmt"
	"testing"

	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
)

type Data struct{ gormDB *reloadableDB }

type reloadableDB struct{ db *gorm.DB }

func newReloadableDB(db *gorm.DB, _ any) *reloadableDB { return &reloadableDB{db: db} }
func (r *reloadableDB) close() {
	if r == nil || r.db == nil {
		return
	}
	if sqlDB, err := r.db.DB(); err == nil {
		_ = sqlDB.Close()
	}
}
func (d *Data) DB() *gorm.DB { return d.gormDB.db }

func openWithDriver(driver, dsn string) (*gorm.DB, error) {
	if driver != "sqlite" {
		return nil, fmt.Errorf("unsupported test database driver %q", driver)
	}
	return gorm.Open(sqlite.Open(dsn), &gorm.Config{})
}

func openIntegrationConfigTestDB(t *testing.T) *gorm.DB {
	t.Helper()
	db, err := openWithDriver("sqlite", "file:"+t.Name()+"?mode=memory&cache=shared")
	if err != nil {
		t.Fatal(err)
	}
	if err := db.AutoMigrate(&integrationConfigPO{}); err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() {
		if sqlDB, err := db.DB(); err == nil {
			_ = sqlDB.Close()
		}
	})
	return db
}

func migrateAll(db *gorm.DB) error {
	if err := db.AutoMigrate(&integrationConfigPO{}); err != nil {
		return err
	}
	for _, step := range Migrations() {
		if err := step.Migrate(db); err != nil {
			return err
		}
	}
	return nil
}
