using Microsoft.AspNetCore.Mvc.Testing;
using VigilCare.Simulation;

/// <summary>
/// Loopback client for WebApplicationFactory tests. Uses X-Test-Role INTEGRATION
/// instead of JWT login (Testing auth scheme ignores Bearer tokens).
/// Uses Server.CreateHandler() to avoid TestServer re-entrancy deadlocks.
/// </summary>
public sealed class TestSimulationClientFactory : ISimulationClientFactory
{
    private readonly WebApplicationFactory<Program> _factory;

    public TestSimulationClientFactory(WebApplicationFactory<Program> factory) =>
        _factory = factory;

    /// <summary>When true, CreateAsync blocks until cancelled — for concurrency/shutdown tests.</summary>
    public bool HangOnCreate { get; set; }

    /// <summary>When true, CreateAsync throws — for failure-path tests.</summary>
    public bool FailOnCreate { get; set; }

    public async Task<VigilCareApiClient> CreateAsync(CancellationToken ct = default)
    {
        if (FailOnCreate)
            throw new HttpRequestException("Login failed (401 Unauthorized): invalid credentials");

        if (HangOnCreate)
            await Task.Delay(Timeout.Infinite, ct);

        var http = new HttpClient(_factory.Server.CreateHandler(), disposeHandler: true)
        {
            BaseAddress = _factory.Server.BaseAddress ?? new Uri("http://localhost"),
        };
        http.DefaultRequestHeaders.Add("X-Test-Role", "INTEGRATION");
        return new VigilCareApiClient(http);
    }
}
