package integration

import (
	"context"
	"fmt"

	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
	"kra/internal/integration/runtimeconfig"
)

type Data struct {
	gormDB *reloadableDB
	store  *runtimeconfig.Store
}

func (d *Data) DB() *gorm.DB {
	if d == nil || d.gormDB == nil {
		return nil
	}
	return d.gormDB.DB()
}

func (d *Data) IntegrationRuntime() *runtimeconfig.Store { return d.store }

type reloadableDB struct{ db *gorm.DB }

func newReloadableDB(db *gorm.DB, _ ...any) *reloadableDB { return &reloadableDB{db: db} }
func (r *reloadableDB) DB() *gorm.DB {
	if r == nil {
		return nil
	}
	return r.db
}
func (r *reloadableDB) WithContext(ctx context.Context) *gorm.DB { return r.db.WithContext(ctx) }

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{})
}
