reinhardt-testkit 0.2.0-rc.1

Core testing infrastructure for Reinhardt framework (no functional crate dependencies)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! Migration Registry Test Fixtures
//! Migration test fixtures and helpers
//!
//! This module provides comprehensive fixtures for testing database migrations
//! and schema operations in Reinhardt applications.
//!
//! ## Fixture Categories
//!
//! ### Unit Testing Fixtures
//!
//! - `` `migration_registry` `` - Isolated `LocalRegistry` for unit testing
//! - `` `test_migration_source` `` - In-memory migration source
//! - `` `in_memory_repository` `` - In-memory migration repository
//!
//! ### Integration Testing Fixtures (requires `testcontainers` feature)
//!
//! - `` `migration_executor` `` - DatabaseMigrationExecutor with PostgreSQL container
//! - `` `postgres_table_creator` `` - PostgreSQL schema management helper
//! - `` `admin_table_creator` `` - Admin panel integration helper (available in `reinhardt-test`)
//!
//! ## Usage Examples
//!
//! ### Unit Testing with LocalRegistry
//!
//! ```rust,no_run
//! # use reinhardt_testkit::fixtures::*;
//! # use reinhardt_db::migrations::Migration;
//! # use rstest::*;
//! // #[rstest]
//! // fn test_migration_registration(migration_registry: LocalRegistry) {
//! //     let migration = Migration::new("0001_initial", "polls");
//! //
//! //     migration_registry.register(migration).unwrap();
//! //     assert_eq!(migration_registry.all_migrations().len(), 1);
//! // }
//! ```
//!
//! ### Integration Testing with PostgresTableCreator
//!
//! ```rust,no_run
//! # use reinhardt_testkit::fixtures::*;
//! # use reinhardt_db::migrations::{Operation, ColumnDefinition, FieldType};
//! # use rstest::*;
//! // #[rstest]
//! // #[tokio::test]
//! // async fn test_with_schema(#[future] postgres_table_creator: PostgresTableCreator) {
//! //     let mut creator = postgres_table_creator.await;
//! //
//! //     // Define schema using Operation enum
//! //     let schema = vec![
//! //         Operation::CreateTable {
//! //             name: "users".to_string(),
//! //             columns: vec![
//! //                 ColumnDefinition::new("id", FieldType::Serial).primary_key(),
//! //                 ColumnDefinition::new("name", FieldType::Text),
//! //             ],
//! //             constraints: vec![],
//! //             without_rowid: None,
//! //             interleave_in_parent: None,
//! //             partition: None,
//! //         },
//! //     ];
//! //
//! //     // Apply schema
//! //     creator.apply(schema).await.unwrap();
//! //
//! //     // Use the database
//! //     let pool = creator.pool();
//! //     // ... test code ...
//! // }
//! ```
//!
//! ## Migration Patterns
//!
//! The new `PostgresTableCreator` and `AdminTableCreator` fixtures promote type-safe
//! schema management using `Operation` enum instead of raw SQL strings. This provides:
//!
//! - **Type safety**: Schema defined using Rust types
//! - **Testability**: Easy to create isolated test databases
//! - **Maintainability**: Schema changes are explicit and reviewable
//! - **Consistency**: Same patterns across all tests

use async_trait::async_trait;
use reinhardt_db::migrations::registry::LocalRegistry;
use reinhardt_db::migrations::{Migration, MigrationRepository, MigrationSource, Result};
use rstest::*;
use std::collections::HashMap;

// TestContainers-related imports (conditional on feature)
#[cfg(feature = "testcontainers")]
use crate::fixtures::testcontainers::postgres_container;
#[cfg(feature = "testcontainers")]
use reinhardt_db::migrations::executor::DatabaseMigrationExecutor;
#[cfg(feature = "testcontainers")]
use reinhardt_db::migrations::{DatabaseConnection, MigrationError, Operation};
#[cfg(feature = "testcontainers")]
use std::sync::Arc;
#[cfg(feature = "testcontainers")]
use testcontainers::{ContainerAsync, GenericImage};

/// Creates a new isolated migration registry for testing
///
/// Each test gets its own empty LocalRegistry instance, ensuring complete
/// isolation between test cases. This avoids the "duplicate distributed_slice"
/// errors that occur with linkme's global registry in test environments.
///
/// # Examples
///
/// ```rust,no_run
/// # use reinhardt_testkit::fixtures::*;
/// # use reinhardt_db::migrations::Migration;
/// # use rstest::*;
/// // #[rstest]
/// // fn test_migration_operations(migration_registry: LocalRegistry) {
/// //     // Registry starts empty
/// //     assert!(migration_registry.all_migrations().is_empty());
/// //
/// //     // Register a migration
/// //     migration_registry.register(Migration::new("0001_initial", "polls")).unwrap();
/// //
/// //     // Verify registration
/// //     assert_eq!(migration_registry.all_migrations().len(), 1);
/// // }
/// ```
#[fixture]
pub fn migration_registry() -> LocalRegistry {
	LocalRegistry::new()
}

/// In-memory migration source for testing
///
/// Provides a simple implementation of `MigrationSource` that stores migrations
/// in memory. Useful for testing migration-related functionality without
/// filesystem or database dependencies.
///
/// # Examples
///
/// ```rust,no_run
/// # use reinhardt_testkit::fixtures::TestMigrationSource;
/// # use reinhardt_db::migrations::{Migration, MigrationSource};
/// # #[tokio::main]
/// # async fn main() {
/// // #[tokio::test]
/// // async fn test_source() {
/// let mut source = TestMigrationSource::new();
/// source.add_migration(Migration::new("0001_initial", "polls"));
///
/// let migrations = source.all_migrations().await.unwrap();
/// assert_eq!(migrations.len(), 1);
/// // }
/// # }
/// ```
pub struct TestMigrationSource {
	migrations: Vec<Migration>,
}

impl TestMigrationSource {
	/// Create a new empty TestMigrationSource
	pub fn new() -> Self {
		Self {
			migrations: Vec::new(),
		}
	}

	/// Create a TestMigrationSource with initial migrations
	pub fn with_migrations(migrations: Vec<Migration>) -> Self {
		Self { migrations }
	}

	/// Add a migration to the source
	pub fn add_migration(&mut self, migration: Migration) {
		self.migrations.push(migration);
	}

	/// Clear all migrations from the source
	pub fn clear(&mut self) {
		self.migrations.clear();
	}

	/// Get the number of migrations
	pub fn len(&self) -> usize {
		self.migrations.len()
	}

	/// Check if the source is empty
	pub fn is_empty(&self) -> bool {
		self.migrations.is_empty()
	}
}

impl Default for TestMigrationSource {
	fn default() -> Self {
		Self::new()
	}
}

#[async_trait]
impl MigrationSource for TestMigrationSource {
	async fn all_migrations(&self) -> Result<Vec<Migration>> {
		Ok(self.migrations.clone())
	}
}

/// In-memory migration repository for testing
///
/// Provides a simple implementation of `MigrationRepository` that stores migrations
/// in memory using a HashMap. Useful for testing migration persistence without
/// actual file I/O.
///
/// # Examples
///
/// ```rust,no_run
/// # use reinhardt_testkit::fixtures::InMemoryRepository;
/// # use reinhardt_db::migrations::{Migration, MigrationRepository};
/// # #[tokio::main]
/// # async fn main() {
/// // #[tokio::test]
/// // async fn test_repository() {
/// let mut repo = InMemoryRepository::new();
///
/// let migration = Migration::new("0001_initial", "polls");
///
/// repo.save(&migration).await.unwrap();
/// let retrieved = repo.get("polls", "0001_initial").await.unwrap();
/// assert_eq!(retrieved.name, "0001_initial");
/// // }
/// # }
/// ```
pub struct InMemoryRepository {
	migrations: HashMap<(String, String), Migration>,
}

impl InMemoryRepository {
	/// Create a new empty InMemoryRepository
	pub fn new() -> Self {
		Self {
			migrations: HashMap::new(),
		}
	}

	/// Create an InMemoryRepository with initial migrations
	pub fn with_migrations(migrations: Vec<Migration>) -> Self {
		let mut repo = Self::new();
		for migration in migrations {
			let key = (migration.app_label.to_string(), migration.name.to_string());
			repo.migrations.insert(key, migration);
		}
		repo
	}

	/// Clear all migrations from the repository
	pub fn clear(&mut self) {
		self.migrations.clear();
	}

	/// Get the number of migrations in the repository
	pub fn len(&self) -> usize {
		self.migrations.len()
	}

	/// Check if the repository is empty
	pub fn is_empty(&self) -> bool {
		self.migrations.is_empty()
	}
}

impl Default for InMemoryRepository {
	fn default() -> Self {
		Self::new()
	}
}

#[async_trait]
impl MigrationRepository for InMemoryRepository {
	async fn save(&mut self, migration: &Migration) -> Result<()> {
		let key = (migration.app_label.to_string(), migration.name.to_string());
		self.migrations.insert(key, migration.clone());
		Ok(())
	}

	async fn get(&self, app_label: &str, name: &str) -> Result<Migration> {
		let key = (app_label.to_string(), name.to_string());
		self.migrations.get(&key).cloned().ok_or_else(|| {
			reinhardt_db::migrations::MigrationError::NotFound(format!("{}.{}", app_label, name))
		})
	}

	async fn list(&self, app_label: &str) -> Result<Vec<Migration>> {
		Ok(self
			.migrations
			.values()
			.filter(|m| m.app_label == app_label)
			.cloned()
			.collect())
	}

	async fn delete(&mut self, app_label: &str, name: &str) -> Result<()> {
		let key = (app_label.to_string(), name.to_string());
		self.migrations.remove(&key).ok_or_else(|| {
			reinhardt_db::migrations::MigrationError::NotFound(format!("{}.{}", app_label, name))
		})?;
		Ok(())
	}
}

/// Creates a new TestMigrationSource for testing
///
/// Provides an empty migration source that can be populated with test migrations.
///
/// # Examples
///
/// ```rust,no_run
/// # use reinhardt_testkit::fixtures::*;
/// # use reinhardt_db::migrations::{Migration, MigrationSource};
/// # use rstest::*;
/// # #[tokio::main]
/// # async fn main() {
/// // #[rstest]
/// // #[tokio::test]
/// // async fn test_with_source(mut test_migration_source: TestMigrationSource) {
/// let mut test_migration_source = TestMigrationSource::new();
/// test_migration_source.add_migration(Migration::new("0001_initial", "polls"));
///
/// let migrations = test_migration_source.all_migrations().await.unwrap();
/// assert_eq!(migrations.len(), 1);
/// // }
/// # }
/// ```
#[fixture]
pub fn test_migration_source() -> TestMigrationSource {
	TestMigrationSource::new()
}

/// Creates a new InMemoryRepository for testing
///
/// Provides an empty migration repository that stores migrations in memory.
///
/// # Examples
///
/// ```rust,no_run
/// # use reinhardt_testkit::fixtures::*;
/// # use reinhardt_db::migrations::{Migration, MigrationRepository};
/// # use rstest::*;
/// # #[tokio::main]
/// # async fn main() {
/// // #[rstest]
/// // #[tokio::test]
/// // async fn test_with_repository(mut in_memory_repository: InMemoryRepository) {
/// let mut in_memory_repository = InMemoryRepository::new();
/// let migration = Migration::new("0001_initial", "polls");
///
/// in_memory_repository.save(&migration).await.unwrap();
/// let retrieved = in_memory_repository.get("polls", "0001_initial").await.unwrap();
/// assert_eq!(retrieved.name, "0001_initial");
/// }
/// ```
#[fixture]
pub fn in_memory_repository() -> InMemoryRepository {
	InMemoryRepository::new()
}

// ============================================================================
// TestContainers-based Migration Executor Fixtures
// ============================================================================

/// Type alias for migration_executor fixture return value
///
/// Contains all elements from postgres_container plus the migration executor:
/// - `DatabaseMigrationExecutor`: Migration executor instance
/// - `ContainerAsync<GenericImage>`: PostgreSQL container
/// - `Arc<PgPool>`: Database connection pool
/// - `u16`: PostgreSQL port
/// - `String`: Database URL
#[cfg(feature = "testcontainers")]
pub type MigrationExecutorFixture = (
	DatabaseMigrationExecutor,
	ContainerAsync<GenericImage>,
	Arc<sqlx::PgPool>,
	u16,
	String,
);

/// Helper for applying database schema migrations in tests with PostgreSQL
///
/// Provides a convenient interface for creating database tables and applying
/// schema operations during test setup. Holds a DatabaseMigrationExecutor
/// and connection pool internally.
///
/// # Examples
///
/// ```rust,no_run
/// # use reinhardt_testkit::fixtures::*;
/// # use reinhardt_db::migrations::{Operation, ColumnDefinition, FieldType};
/// # use rstest::*;
/// #[rstest]
/// #[tokio::test]
/// async fn test_with_schema(#[future] postgres_table_creator: PostgresTableCreator) {
///     let mut creator = postgres_table_creator.await;
///
///     let schema = vec![
///         Operation::CreateTable {
///             name: "users".to_string(),
///             columns: vec![
///                 ColumnDefinition::new("id", FieldType::Integer),
///                 ColumnDefinition::new("name", FieldType::Text),
///             ],
///             constraints: vec![],
///             without_rowid: None,
///             interleave_in_parent: None,
///             partition: None,
///         },
///     ];
///
///     creator.apply(schema).await.unwrap();
///
///     let pool = creator.pool();
///     // Run tests using pool...
/// }
/// ```
#[cfg(feature = "testcontainers")]
pub struct PostgresTableCreator {
	executor: DatabaseMigrationExecutor,
	pool: Arc<sqlx::PgPool>,
	container: ContainerAsync<GenericImage>,
	port: u16,
	url: String,
}

#[cfg(feature = "testcontainers")]
impl PostgresTableCreator {
	/// Create a new TableCreator
	pub fn new(
		executor: DatabaseMigrationExecutor,
		container: ContainerAsync<GenericImage>,
		pool: Arc<sqlx::PgPool>,
		port: u16,
		url: String,
	) -> Self {
		Self {
			executor,
			pool,
			container,
			port,
			url,
		}
	}

	/// Apply schema operations by creating and executing a migration
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// # use reinhardt_testkit::fixtures::*;
	/// # use reinhardt_db::migrations::{Operation, ColumnDefinition, FieldType};
	/// # async fn example(mut creator: PostgresTableCreator) {
	/// let schema = vec![
	///     Operation::CreateTable {
	///         name: "products".to_string(),
	///         columns: vec![
	///             ColumnDefinition::new("id", FieldType::Integer),
	///             ColumnDefinition::new("name", FieldType::Text),
	///         ],
	///         constraints: vec![],
	///         without_rowid: None,
	///         interleave_in_parent: None,
	///         partition: None,
	///     },
	/// ];
	///
	/// creator.apply(schema).await.unwrap();
	/// # }
	/// ```
	pub async fn apply(&mut self, schema: Vec<Operation>) -> Result<()> {
		let mut migration = Migration::new("0001_test_schema", "testapp");

		for operation in schema {
			migration = migration.add_operation(operation);
		}

		self.executor
			.apply_migrations(&[migration])
			.await
			.expect("Failed to apply test schema migrations");

		Ok(())
	}

	/// Get a reference to the database connection pool
	pub fn pool(&self) -> &Arc<sqlx::PgPool> {
		&self.pool
	}

	/// Get the database URL
	pub fn url(&self) -> &str {
		&self.url
	}

	/// Get the database port
	pub fn port(&self) -> u16 {
		self.port
	}

	/// Get a reference to the container
	///
	/// This is useful for advanced test scenarios that need direct container access.
	pub fn container(&self) -> &ContainerAsync<GenericImage> {
		&self.container
	}

	/// Insert data into a table using reinhardt-query
	///
	/// This method provides a convenient way to insert test data using type-safe
	/// reinhardt-query builders instead of raw SQL strings.
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// # use reinhardt_testkit::fixtures::*;
	/// # use reinhardt_query::prelude::Value;
	/// # async fn example(creator: &PostgresTableCreator) {
	/// creator.insert_data(
	///     "users",
	///     vec!["id", "name", "email"],
	///     vec![
	///         vec![
	///             Value::Int(Some(1)),
	///             Value::String(Some(Box::new("Alice".to_string()))),
	///             Value::String(Some(Box::new("alice@example.com".to_string()))),
	///         ],
	///     ],
	/// ).await.unwrap();
	/// # }
	/// ```
	pub async fn insert_data(
		&self,
		table: &str,
		columns: Vec<&str>,
		values: Vec<Vec<reinhardt_query::prelude::Value>>,
	) -> Result<()> {
		use reinhardt_query::prelude::{Alias, PostgresQueryBuilder, Query, QueryStatementBuilder};

		for row_values in values {
			let mut query = Query::insert();
			query
				.into_table(Alias::new(table))
				.columns(columns.iter().map(|&c| Alias::new(c)));

			query.values_panic(row_values);

			// Build SQL string
			let sql = query.to_string(PostgresQueryBuilder::new());

			sqlx::query(&sql)
				.execute(self.pool.as_ref())
				.await
				.map_err(MigrationError::SqlError)?;
		}
		Ok(())
	}

	/// Execute custom SQL (fallback for complex cases)
	///
	/// This method allows executing arbitrary SQL statements when reinhardt-query
	/// is insufficient for complex schema operations or PostgreSQL-specific features.
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// # use reinhardt_testkit::fixtures::*;
	/// # async fn example(creator: &PostgresTableCreator) {
	/// // PostgreSQL-specific feature
	/// creator.execute_sql(
	///     "CREATE TABLE test (id SERIAL PRIMARY KEY) WITH (autovacuum_enabled = false)"
	/// ).await.unwrap();
	/// # }
	/// ```
	pub async fn execute_sql(&self, sql: &str) -> Result<sqlx::postgres::PgQueryResult> {
		sqlx::query(sql)
			.execute(self.pool.as_ref())
			.await
			.map_err(MigrationError::SqlError)
	}

	/// Begin a transaction for advanced test scenarios
	///
	/// This is useful for testing two-phase commit (2PC) or other transaction-based
	/// operations.
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// # use reinhardt_testkit::fixtures::*;
	/// # async fn example(creator: &PostgresTableCreator) {
	/// let mut tx = creator.begin_transaction().await.unwrap();
	/// // Perform transactional operations...
	/// tx.commit().await.unwrap();
	/// # }
	/// ```
	pub async fn begin_transaction(&self) -> Result<sqlx::Transaction<'_, sqlx::Postgres>> {
		self.pool.begin().await.map_err(MigrationError::SqlError)
	}
}

// ============================================================================
// Migration Executor and Table Creator Fixtures
// ============================================================================

/// Creates a DatabaseMigrationExecutor connected to a test PostgreSQL container
///
/// This fixture combines postgres_container with migration executor creation,
/// providing a ready-to-use migration executor for tests.
///
/// # Type Signature
///
/// Returns `MigrationExecutorFixture`:
/// - `DatabaseMigrationExecutor`: Migration executor instance
/// - `ContainerAsync<GenericImage>`: PostgreSQL container
/// - `Arc<PgPool>`: Database connection pool
/// - `u16`: PostgreSQL port
/// - `String`: Database URL
///
/// # Examples
///
/// ```rust,no_run
/// # use reinhardt_testkit::fixtures::*;
/// # use reinhardt_db::migrations::Migration;
/// # use rstest::*;
/// #[rstest]
/// #[tokio::test]
/// async fn test_with_executor(
///     #[future] migration_executor: MigrationExecutorFixture
/// ) {
///     let (mut executor, _container, _pool, _port, _url) = migration_executor.await;
///
///     let migration = Migration::new("0001_test", "testapp");
///     executor.apply_migrations(&[migration]).await.unwrap();
/// }
/// ```
#[cfg(feature = "testcontainers")]
#[fixture]
pub async fn migration_executor(
	#[future] postgres_container: (ContainerAsync<GenericImage>, Arc<sqlx::PgPool>, u16, String),
) -> MigrationExecutorFixture {
	let (container, pool, port, url) = postgres_container.await;

	let connection = DatabaseConnection::connect_postgres(&url)
		.await
		.expect("Failed to connect to test database");

	let executor = DatabaseMigrationExecutor::new(connection);

	(executor, container, pool, port, url)
}

/// Creates a PostgresTableCreator for applying test schemas
///
/// This fixture combines migration_executor with a convenient helper structure
/// for applying database schema operations in PostgreSQL tests.
///
/// # Type Signature
///
/// Returns `` `PostgresTableCreator` ``:
/// - Helper with methods to apply schema operations
/// - Provides access to connection pool, URL, and port
/// - Includes methods for data insertion and custom SQL execution
///
/// # Examples
///
/// ```rust,no_run
/// # use reinhardt_testkit::fixtures::*;
/// # use reinhardt_db::migrations::{Operation, ColumnDefinition, FieldType};
/// # use rstest::*;
/// #[rstest]
/// #[tokio::test]
/// async fn test_with_creator(#[future] postgres_table_creator: PostgresTableCreator) {
///     let mut creator = postgres_table_creator.await;
///
///     let schema = vec![
///         Operation::CreateTable {
///             name: "test_table".to_string(),
///             columns: vec![
///                 ColumnDefinition::new("id", FieldType::Integer),
///             ],
///             constraints: vec![],
///             without_rowid: None,
///             interleave_in_parent: None,
///             partition: None,
///         },
///     ];
///
///     creator.apply(schema).await.unwrap();
///     let pool = creator.pool();
///     // Use pool for testing...
/// }
/// ```
#[cfg(feature = "testcontainers")]
#[fixture]
pub async fn postgres_table_creator(
	#[future] migration_executor: MigrationExecutorFixture,
) -> PostgresTableCreator {
	let (executor, container, pool, port, url) = migration_executor.await;
	PostgresTableCreator::new(executor, container, pool, port, url)
}

#[cfg(test)]
mod tests {
	use super::*;
	use reinhardt_db::migrations::Migration;
	use reinhardt_db::migrations::registry::MigrationRegistry;

	#[rstest]
	fn test_migration_registry_fixture(migration_registry: LocalRegistry) {
		assert!(migration_registry.all_migrations().is_empty());
	}

	#[rstest]
	fn test_registry_isolation_between_tests(migration_registry: LocalRegistry) {
		// This test runs independently - registry should be empty
		assert_eq!(migration_registry.all_migrations().len(), 0);

		migration_registry
			.register(Migration::new("0001_initial", "test_app"))
			.unwrap();

		assert_eq!(migration_registry.all_migrations().len(), 1);
	}

	#[rstest]
	fn test_another_isolated_test(migration_registry: LocalRegistry) {
		// Even though previous test registered a migration,
		// this new fixture instance should be empty
		assert_eq!(migration_registry.all_migrations().len(), 0);
	}

	#[cfg(feature = "testcontainers")]
	mod testcontainer_fixtures {
		use super::*;
		use reinhardt_db::migrations::{ColumnDefinition, DatabaseType, FieldType, Operation};

		#[rstest]
		#[tokio::test]
		async fn test_migration_executor_fixture(
			#[future] migration_executor: MigrationExecutorFixture,
		) {
			let (executor, _container, _pool, _port, _url) = migration_executor.await;

			// Verify executor is connected to PostgreSQL
			assert_eq!(executor.database_type(), DatabaseType::Postgres);
		}

		#[rstest]
		#[tokio::test]
		async fn test_postgres_table_creator_fixture(
			#[future] postgres_table_creator: PostgresTableCreator,
		) {
			let mut creator = postgres_table_creator.await;

			// Define schema directly in test
			let schema = vec![Operation::CreateTable {
				name: "fixture_test_table".to_string(),
				columns: vec![
					ColumnDefinition::new("id", FieldType::Integer),
					ColumnDefinition::new("value", FieldType::Text),
				],
				constraints: vec![],
				without_rowid: None,
				interleave_in_parent: None,
				partition: None,
			}];

			// Apply schema
			creator.apply(schema).await.unwrap();

			// Verify table was created
			let pool = creator.pool();
			let result = sqlx::query("SELECT * FROM fixture_test_table")
				.fetch_all(pool.as_ref())
				.await
				.unwrap();

			assert!(result.is_empty());
		}
	}
}