using System.Net;
using System.Net.Http.Json;
using CashLineERP.Contracts.Reporting;

namespace CashLineERP.Api.Tests;

public sealed class ReportingSnapshotQaTests : IClassFixture<ApiTestFactory>
{
    private readonly HttpClient _client;

    public ReportingSnapshotQaTests(ApiTestFactory factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task Reporting_Snapshot_Endpoints_Generate_List_And_Return_History_Detail()
    {
        await _client.AuthenticateAsInternalAsync();

        var createResponse = await _client.PostAsJsonAsync("/api/v1/reports/snapshots", new CreateReportingSnapshotRequest(
            ReportCode: "CORE_OPERATIONS",
            DateFrom: new DateOnly(2026, 4, 1),
            DateTo: new DateOnly(2026, 4, 30),
            AsOfDate: null,
            Notes: "HTTP operations snapshot"));
        Assert.Equal(HttpStatusCode.OK, createResponse.StatusCode);

        var created = await createResponse.Content.ReadFromJsonAsync<ReportingSnapshotResponse>();
        Assert.NotNull(created);
        Assert.Equal("CORE_OPERATIONS", created!.ReportCode);
        Assert.Contains("ActivityDate,ActivityType,DocumentNumber", created.CsvPayloadText, StringComparison.Ordinal);

        var listResponse = await _client.GetAsync("/api/v1/reports/snapshots?reportCode=CORE_OPERATIONS");
        Assert.Equal(HttpStatusCode.OK, listResponse.StatusCode);
        var history = await listResponse.Content.ReadFromJsonAsync<IReadOnlyCollection<ReportingSnapshotSummaryResponse>>();
        Assert.NotNull(history);
        Assert.Contains(history!, item => item.ReportingSnapshotId == created.ReportingSnapshotId);

        var detailResponse = await _client.GetAsync($"/api/v1/reports/snapshots/{created.ReportingSnapshotId}");
        Assert.Equal(HttpStatusCode.OK, detailResponse.StatusCode);
        var detail = await detailResponse.Content.ReadFromJsonAsync<ReportingSnapshotResponse>();
        Assert.NotNull(detail);
        Assert.Equal(created.SnapshotNumber, detail!.SnapshotNumber);
        Assert.Contains("purchaseRequisitionCount", detail.JsonPayloadText, StringComparison.Ordinal);
    }
}
