//go:build e2e

// Package testkit provides E2E-specific test harnesses shared across the
// e2e test suite. It is compiled with the //go:build e2e tag.
package testkit

import (
	"context"
	"database/sql"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	"github.com/tidbcloud/AgentTeam/internal/coredb/testkit/tidbruntime"
	"github.com/tidbcloud/AgentTeam/internal/tidb"
)

// StartTiDBAtMigration returns a DSN for an isolated TiDB database driven to
// the specified migration version via the real registered migration FS. The
// root DSN must point to a running TiDB test runtime (typically obtained from
// a TiDBRuntimeFixture.RootDSN call).
//
// The returned database has the schema shape that production would have at
// the given migration version, including any tables/columnons that have been
// dropped or renamed by later migrations (e.g., directories still exists at
// v242). Use this to test migration N's behavior on a real prior-state
// database, rather than hand-modifying a fresh bootstrap snapshot.
func StartTiDBAtMigration(t *testing.T, rootDSN string, version int64) string {
	t.Helper()

	dsn := tidbruntime.StartIsolatedTiDBWithRootDSN(t, rootDSN)

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()

	sqlDB, err := tidbruntime.OpenTiDBContext(ctx, dsn)
	require.NoError(t, err)
	defer func() {
		if err := sqlDB.Close(); err != nil {
			t.Errorf("close migration harness db: %v", err)
		}
	}()

	require.NoErrorf(t, tidb.ApplyVersionedMigrationsUpToForTesting(ctx, sqlDB, version),
		"drive tidb to migration %d", version)

	return dsn
}

// OpenE2EDB opens a *sql.DB for the given DSN with the test's lifetime tied
// cleanup. Convenience wrapper for E2E tests that need direct SQL access.
func OpenE2EDB(t *testing.T, dsn string) *sql.DB {
	t.Helper()
	return tidbruntime.OpenTiDB(t, dsn)
}
