using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;

public class ApiFixture : WebApplicationFactory<Program>, IAsyncLifetime
{
    // Override configuration to point at a test database — never run tests against
    // the development database; a botched rollback could corrupt seed data.
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseEnvironment("Testing");
        builder.ConfigureAppConfiguration((_, config) =>
        {
            config.AddInMemoryCollection(new Dictionary<string, string?>
            {
                ["ConnectionStrings:DefaultConnection"] =
                    "Host=localhost;Port=5436;Database=vigilcare_test;Username=postgres;Password=password",
                ["Redis:ConnectionString"] = "localhost:6382,defaultDatabase=1,allowAdmin=true",
                ["RabbitMq:Host"] = "localhost",
                ["RabbitMq:Port"] = "5674",
                ["RabbitMq:Username"] = "guest",
                ["RabbitMq:Password"] = "guest",
                ["RabbitMq:PagingAckTimeoutMs"] = "5000",
                ["Fhir:ApiKey"] = "dev-integration-key-change-in-production",
                ["ApiKey:Gateway"] = GatewayAuthHelper.DevGatewayKey,
            });

            config.AddJsonFile("appsettings.Testing.json", optional: true, reloadOnChange: false);
        });

        builder.ConfigureServices(services =>
        {
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = TestingAuthHandler.SchemeName;
                options.DefaultChallengeScheme = TestingAuthHandler.SchemeName;
            })
            .AddScheme<AuthenticationSchemeOptions, TestingAuthHandler>(
                TestingAuthHandler.SchemeName, _ => { });
        });
    }

    public async Task InitializeAsync()
    {
        // Apply migrations and clean stale data before the host starts — background
        // services such as ThresholdCacheLoader query the database during StartAsync,
        // so the reset must happen while no hosted service holds a lock.
        var connectionString = "Host=localhost;Port=5436;Database=vigilcare_test;Username=postgres;Password=password";
        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseNpgsql(connectionString)
            .Options;
        await using (var migrateDb = new AppDbContext(options))
        {
            await migrateDb.Database.MigrateAsync();
            await DbResetHelper.ResetAsync(migrateDb);
        }

        using var scope = Services.CreateScope();
        var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
        var server = redis.GetServer(redis.GetEndPoints().First());
        await server.FlushDatabaseAsync(1);
    }

    protected override void ConfigureClient(HttpClient client)
    {
        base.ConfigureClient(client);
        client.DefaultRequestHeaders.Add("X-Test-Role", "ADMIN");
    }

    public new async Task DisposeAsync()
    {
        await base.DisposeAsync();
    }
}
