using CashLineERP.Application.Reporting;
using CashLineERP.Contracts.Reporting;
using CashLineERP.Infrastructure.Persistence.Repositories;

namespace CashLineERP.Api.Tests;

public sealed class ReportingSnapshotServiceQaTests
{
    [Fact]
    public void Reporting_Snapshot_Generation_Persists_Finance_And_Aging_History()
    {
        using var dbContext = QaDbContextFactory.CreateContext();

        var reportingService = new CoreReportingService(new CoreReportingRepository(dbContext));

        var financeSnapshot = reportingService.GenerateReportingSnapshot(4, new CreateReportingSnapshotRequest(
            ReportCode: "CORE_FINANCE",
            DateFrom: new DateOnly(2026, 4, 1),
            DateTo: new DateOnly(2026, 4, 30),
            AsOfDate: null,
            Notes: "April finance snapshot"));

        Assert.Equal("CORE_FINANCE", financeSnapshot.ReportCode);
        Assert.Equal(new DateOnly(2026, 4, 1), financeSnapshot.DateFrom);
        Assert.Equal(new DateOnly(2026, 4, 30), financeSnapshot.DateTo);
        Assert.True(financeSnapshot.RowCount >= 1);
        Assert.Contains("postedAccountsPayableBillCount", financeSnapshot.JsonPayloadText, StringComparison.Ordinal);
        Assert.Contains("BusinessDate,ReportSection,DocumentType", financeSnapshot.CsvPayloadText, StringComparison.Ordinal);

        var agingSnapshot = reportingService.GenerateReportingSnapshot(4, new CreateReportingSnapshotRequest(
            ReportCode: "AR_AGING",
            DateFrom: null,
            DateTo: null,
            AsOfDate: new DateOnly(2026, 4, 30),
            Notes: "April AR aging snapshot"));

        Assert.Equal("AR_AGING", agingSnapshot.ReportCode);
        Assert.Equal(new DateOnly(2026, 4, 30), agingSnapshot.AsOfDate);
        Assert.Contains("\"ledgerSideCode\":\"AR\"", agingSnapshot.JsonPayloadText, StringComparison.Ordinal);
        Assert.Contains("LedgerSide,DocumentType,DocumentNumber", agingSnapshot.CsvPayloadText, StringComparison.Ordinal);

        var history = reportingService.GetReportingSnapshots();
        Assert.True(history.Count >= 2);
        Assert.Equal(agingSnapshot.ReportingSnapshotId, history.First().ReportingSnapshotId);

        var detail = reportingService.GetReportingSnapshot(financeSnapshot.ReportingSnapshotId);
        Assert.NotNull(detail);
        Assert.Equal(financeSnapshot.SnapshotNumber, detail!.SnapshotNumber);
        Assert.Equal("April finance snapshot", detail.Notes);
    }
}
