using ColaFlow.Modules.Identity.Application.Services;
using ColaFlow.Modules.Identity.Infrastructure.Services;
using Microsoft.Extensions.DependencyInjection;

namespace ColaFlow.Modules.Identity.IntegrationTests.Infrastructure;

/// <summary>
/// Database Fixture for In-Memory Database Tests
/// Implements IClassFixture for xUnit test lifecycle management
/// Each test class gets its own isolated database instance
/// </summary>
public class DatabaseFixture : IDisposable
{
    public ColaFlowWebApplicationFactory Factory { get; } = new(useInMemoryDatabase: true);

    // Note: Client property is kept for backward compatibility but creates new instances
    // Tests should call CreateClient() for isolation to avoid shared state issues
    public HttpClient Client => CreateClient();

    // Use In-Memory Database for fast, isolated tests

    /// <summary>
    /// Creates a new HttpClient for each test to ensure test isolation
    /// Prevents Authorization header sharing between tests
    /// </summary>
    public HttpClient CreateClient()
    {
        return Factory.CreateClient();
    }

    /// <summary>
    /// Gets the MockEmailService from the DI container for testing
    /// </summary>
    public MockEmailService GetEmailService()
    {
        var scope = Factory.Services.CreateScope();
        var emailService = scope.ServiceProvider.GetRequiredService<IEmailService>();
        return (MockEmailService)emailService;
    }

    public void Dispose()
    {
        Factory?.Dispose();
        GC.SuppressFinalize(this);
    }
}
