using System.Net;
using System.Net.Http.Json;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;

[Collection("Integration")]
public class OperationsApiTests : IAsyncLifetime
{
    private readonly ApiFixture _fixture;
    private readonly HttpClient _client;

    public OperationsApiTests(ApiFixture fixture)
    {
        _fixture = fixture;
        _client = fixture.CreateClient();
    }

    public async Task InitializeAsync()
    {
        _client.AsAdmin();
        using var scope = _fixture.Services.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
        await DbResetHelper.ResetAsync(db);
        await GatewayRegistrySeeder.SeedAsync(db);

        var gateway = await db.WardGateways.FindAsync(GatewayRegistrySeeder.DemoGatewayId);
        gateway!.RecordHeartbeat(GatewayStatus.Degraded, 847, DateTimeOffset.UtcNow.AddMinutes(-5));
        await db.SaveChangesAsync();
    }

    public Task DisposeAsync() => Task.CompletedTask;

    [Fact]
    public async Task GetFleet_ReturnsAllGateways()
    {
        var resp = await _client.GetAsync("/api/v1/operations/gateways");
        resp.StatusCode.Should().Be(HttpStatusCode.OK);
        var body = await resp.Content.ReadFromJsonAsync<ApiResponse<List<GatewayFleetItem>>>();
        body!.Data.Should().NotBeEmpty();
    }

    [Fact]
    public async Task GetFleet_FilterDegraded()
    {
        var resp = await _client.GetAsync("/api/v1/operations/gateways?status=DEGRADED");
        var body = await resp.Content.ReadFromJsonAsync<ApiResponse<List<GatewayFleetItem>>>();
        body!.Data.Should().OnlyContain(g => g.Status == "DEGRADED");
    }

    [Fact]
    public async Task GetSiteSummary_CountsByStatus()
    {
        var resp = await _client.GetAsync(
            $"/api/v1/operations/sites/{GatewayRegistrySeeder.DemoSiteId}/summary");
        var body = await resp.Content.ReadFromJsonAsync<ApiResponse<SiteGatewaySummaryResponse>>();
        body!.Data!.TotalGateways.Should().BeGreaterThan(0);
        body.Data.Degraded.Should().BeGreaterThanOrEqualTo(1);
    }

    [Fact]
    public async Task GetGatewayDetail_IncludesSyncHistory()
    {
        var resp = await _client.GetAsync(
            $"/api/v1/operations/gateways/{GatewayRegistrySeeder.DemoGatewayId}");
        resp.StatusCode.Should().Be(HttpStatusCode.OK);
        var body = await resp.Content.ReadFromJsonAsync<ApiResponse<GatewayDetailResponse>>();
        body!.Data!.Gateway.GatewayCode.Should().Be("GW-ICU-3B");
        body.Data.RecentBatches.Should().NotBeNull();
    }
}