package execution

import (
	"context"
	"os"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

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

var roleManagementTiDB = *testkit.NewTiDBCoreDBFixture(testkit.TiDBTestRuntimeFullCluster)

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

// startRoleManagementRollbackDB is for transaction-scoped state only. The
// package boundary guard rejects effects that rollback cannot isolate.
func startRoleManagementRollbackDB(t *testing.T, ctx context.Context) coredb.DB {
	t.Helper()
	return roleManagementTiDB.SerializedRollbackDB(t, ctx)
}

func mustExecRoleManagement(t testing.TB, db coredb.QueryExecer, query string, args ...any) {
	t.Helper()
	_, err := db.Exec(context.Background(), query, args...)
	require.NoError(t, err)
}

func seedExecutionApproval(
	t testing.TB,
	db coredb.QueryExecer,
	workspaceID, memberID, approvalID string,
	now time.Time,
) {
	t.Helper()
	seedExecutionWorkspaceAndApproval(t, db, workspaceID, memberID, approvalID, now)
}

func seedExecutionWorkspaceAndApproval(
	t testing.TB,
	db coredb.QueryExecer,
	workspaceID, memberID, approvalID string,
	now time.Time,
) {
	t.Helper()
	userID := "usr_" + memberID
	orgID := "org_" + workspaceID
	mustExecRoleManagement(t, db, `
INSERT INTO users (id,email,name,display_name,password_hash,created_at,updated_at)
VALUES ($1,$2,$1,$1,'hash',$3,$3)`,
		userID, userID+"@example.com", now)
	mustExecRoleManagement(t, db, `
INSERT INTO organizations (id,slug,name,created_by_user_id,created_at,updated_at)
VALUES ($1,$1,$1,$2,$3,$3)`, orgID, userID, now)
	mustExecRoleManagement(t, db, `
INSERT INTO workspaces (id,organization_id,slug,name,created_at,updated_at)
VALUES ($1,$2,$1,$1,$3,$3)`, workspaceID, orgID, now)
	mustExecRoleManagement(t, db, `
INSERT INTO members (id,workspace_id,type,display_name,status,created_at,updated_at)
VALUES ($1,$2,'agent',$1,'active',$3,$3)`, memberID, workspaceID, now)
	mustExecRoleManagement(t, db, `
INSERT INTO approval_instances (
  id,workspace_id,subject_type,subject_ref,subject_version,
  payload,payload_digest,idempotency_key,pending_key,projected_version,
  applicant_member_id,state,decision,decision_reason,decided_by_member_id,
  version,correlation_id,created_at,updated_at,decided_at
) VALUES (
  $1,$2,'role_management',$1,1,
  '{"schemaVersion":1}',$3,NULL,NULL,0,
  $4,'pending','','',NULL,
  1,'',$5,$5,NULL
)`, approvalID, workspaceID,
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
		memberID, now)
}
