package testutil

import (
	"context"
	"fmt"
	"path/filepath"
	"sync"
	"testing"

	"sub2api-cn-relay-manager/internal/store/sqlite"
)

var sqliteOpenMu sync.Mutex

func SQLiteTestDSN(t testing.TB, fileName string, disableForeignKeys bool) string {
	t.Helper()

	dsn := fmt.Sprintf("file:%s?_busy_timeout=5000", filepath.ToSlash(filepath.Join(t.TempDir(), fileName)))
	if disableForeignKeys {
		dsn += "&_pragma=foreign_keys(0)"
	}
	return dsn
}

func OpenSQLiteStore(t testing.TB, dsn string) *sqlite.DB {
	t.Helper()

	sqliteOpenMu.Lock()
	store, err := sqlite.Open(context.Background(), dsn)
	sqliteOpenMu.Unlock()
	if err != nil {
		t.Fatalf("sqlite.Open() error = %v", err)
	}
	return store
}

func CloseSQLiteStore(t testing.TB, store *sqlite.DB) {
	t.Helper()
	if err := store.Close(); err != nil {
		t.Fatalf("store.Close() error = %v", err)
	}
}
