using System.Net.Http.Json; using HealthApp.Contracts; using HealthApp.Infrastructure; using Microsoft.Extensions.DependencyInjection; using Npgsql; using Observation.AcceptanceTests; using Xunit; namespace HealthApp.AcceptanceTests; public sealed class SnapshotTests(ObservationApiFixture fixture) : IClassFixture { [Fact] public async Task Overview_is_coherent_and_next_snapshot_sees_commits() { using var create=await fixture.Client.PostAsJsonAsync("/api/patients",new{name="Before",dateOfBirth="1980-01-01"});var p=(await create.Content.ReadFromJsonAsync())!; using var record=await fixture.Client.PostAsJsonAsync($"/api/patients/{p.PatientId}/observations",new{measuredAt="2026-09-12T08:00:00",systolic=120,diastolic=80,pulse=60});var o=(await record.Content.ReadFromJsonAsync())!; var captured=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);var resume=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var armed=1;var selectedCount=0;var releasedBeforeReturn=false; fixture.ConfigureServices=services=>{ var pd=services.Last(d=>d.ServiceType==typeof(ProfileQueries));services.Remove(pd); services.AddScoped(sp=>new PausingProfile((ProfileQueries)pd.ImplementationFactory!(sp),async()=>{if(Interlocked.Exchange(ref armed,0)==1){captured.SetResult();await resume.Task;}})); var od=services.Last(d=>d.ServiceType==typeof(ObservationQueries));services.Remove(od); services.AddScoped(sp=>new CountingObservations((ObservationQueries)od.ImplementationFactory!(sp),()=>Interlocked.Increment(ref selectedCount))); var ad=services.Last(d=>d.ServiceType==typeof(AnalyticsQueries));services.Remove(ad); services.AddScoped(sp=>new CheckingAnalytics((AnalyticsQueries)ActivatorUtilities.CreateInstance(sp,ad.ImplementationType!),()=>releasedBeforeReturn=!sp.GetRequiredService().Active)); }; await fixture.RestartHostsAsync(); try { var path=$"/api/patients/{p.PatientId}/overview?from=2026-09-01&to=2026-09-30"; var reading=fixture.Client.GetFromJsonAsync(path); await captured.Task.WaitAsync(TimeSpan.FromSeconds(10)); await using(var c=new NpgsqlConnection(fixture.ConnectionString)) {await c.OpenAsync();await using var t=await c.BeginTransactionAsync();var cmd=new NpgsqlCommand("UPDATE profile.patient SET name='After' WHERE patient_id=@p; UPDATE observations.observation SET systolic=180 WHERE observation_id=@o",c,t);cmd.Parameters.AddWithValue("p",p.PatientId);cmd.Parameters.AddWithValue("o",o.ObservationId);await cmd.ExecuteNonQueryAsync();await t.CommitAsync();} resume.SetResult();var first=(await reading)!; Assert.Equal("Before",first.Patient.Name);Assert.Equal(120,first.LatestObservation!.Systolic);Assert.Equal(120m,first.Insight!.AverageSystolic);Assert.Equal(1,selectedCount);Assert.True(releasedBeforeReturn); var next=(await fixture.Client.GetFromJsonAsync(path))!;Assert.Equal("After",next.Patient.Name);Assert.Equal(180,next.LatestObservation!.Systolic);Assert.Equal(180m,next.Insight!.AverageSystolic); } finally{resume.TrySetResult();fixture.ConfigureServices=null;await fixture.RestartHostsAsync();} } private sealed class PausingProfile(ProfileQueries inner,Func pause) : ProfileQueries { public Task ResolveAccountAsync(string a,CancellationToken ct)=>inner.ResolveAccountAsync(a,ct); public async Task GetAsync(AuthorizedPatientContext s,CancellationToken ct){var p=await inner.GetAsync(s,ct);await pause();return p;} } private sealed class CountingObservations(ObservationQueries inner,Action count) : ObservationQueries { public Task ResolveOwnerAsync(Guid id,CancellationToken ct)=>inner.ResolveOwnerAsync(id,ct); public Task GetAsync(AuthorizedPatientContext s,Guid id,CancellationToken ct)=>inner.GetAsync(s,id,ct); public Task LatestAsync(AuthorizedPatientContext s,CancellationToken ct)=>inner.LatestAsync(s,ct); public Task> SelectedAsync(AuthorizedPatientContext s,DateTime f,DateTime t,ContextSelection c,CancellationToken ct){count();return inner.SelectedAsync(s,f,t,c,ct);} } private sealed class CheckingAnalytics(AnalyticsQueries inner,Action check) : AnalyticsQueries { public async Task InsightAsync(AuthorizedPatientContext s,DateTime f,DateTime t,ContextSelection c,CancellationToken ct){var v=await inner.InsightAsync(s,f,t,c,ct);check();return v;} public Task TrendAsync(AuthorizedPatientContext s,DateTime f,DateTime t,ContextSelection c,CancellationToken ct)=>inner.TrendAsync(s,f,t,c,ct); } }