package run_test

import (
	"context"
	"fmt"
	"os"
	"testing"

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

var workflowRunTiDB testkit.TiDBCoreDBFixture

func TestMain(m *testing.M) {
	os.Exit(testkit.RunTestsWithTiDBCoreDBFixture(m, "workflow_run_store", &workflowRunTiDB))
}

func startRollbackDB(t *testing.T, ctx context.Context) coredb.DB {
	t.Helper()
	// These tests only mutate transaction-scoped rows. The fixture guard rejects
	// t.Parallel, DDL, global state, failpoints, and environment mutation because
	// those effects cannot be isolated by rollback on the shared database.
	return workflowRunTiDB.SerializedRollbackDB(t, ctx)
}

// startCommittedDB returns one serialized package database with a real
// connection pool. Every fixture in this package is rooted under the explicit
// org_run_/org_iso2_ namespaces; deleting those organizations cascades all
// workspace-owned workflow state before the next test while preserving the
// migrated template's seed rows.
func startCommittedDB(t *testing.T, ctx context.Context) coredb.DB {
	t.Helper()
	return workflowRunTiDB.SerializedCommittedDB(t, ctx, resetCommittedWorkflowRunDB)
}

func resetCommittedWorkflowRunDB(ctx context.Context, db coredb.DB) error {
	return coredb.WithTx(ctx, db, func(tx coredb.Tx) error {
		// These tables also reference the fixture member without ON DELETE
		// CASCADE, so remove their workspace-owned rows before deleting the
		// organization root.
		for _, table := range []string{"scope_messages", "scopes"} {
			if _, err := tx.Exec(ctx, `DELETE FROM `+table+`
WHERE workspace_id LIKE 'wsp=_run=_%' ESCAPE '=' OR workspace_id LIKE 'wsp=_iso2=_%' ESCAPE '='`); err != nil {
				return fmt.Errorf("delete workflowrun test %s: %w", table, err)
			}
		}
		if _, err := tx.Exec(ctx, `
DELETE FROM organizations
WHERE id LIKE 'org=_run=_%' ESCAPE '=' OR id LIKE 'org=_iso2=_%' ESCAPE '='`); err != nil {
			return fmt.Errorf("delete workflowrun test organizations: %w", err)
		}
		if _, err := tx.Exec(ctx, `
DELETE FROM users
WHERE id LIKE 'usr=_run=_%' ESCAPE '=' OR id LIKE 'usr=_iso2=_%' ESCAPE '='`); err != nil {
			return fmt.Errorf("delete workflowrun test users: %w", err)
		}

		var remaining int
		if err := tx.QueryRow(ctx, `
SELECT
  (SELECT COUNT(*) FROM organizations WHERE id LIKE 'org=_run=_%' ESCAPE '=' OR id LIKE 'org=_iso2=_%' ESCAPE '=') +
  (SELECT COUNT(*) FROM workspaces WHERE id LIKE 'wsp=_run=_%' ESCAPE '=' OR id LIKE 'wsp=_iso2=_%' ESCAPE '=') +
  (SELECT COUNT(*) FROM users WHERE id LIKE 'usr=_run=_%' ESCAPE '=' OR id LIKE 'usr=_iso2=_%' ESCAPE '=')`).Scan(&remaining); err != nil {
			return fmt.Errorf("verify workflowrun test roots: %w", err)
		}
		if remaining != 0 {
			return fmt.Errorf("workflowrun test reset left %d owned roots", remaining)
		}
		return nil
	})
}
