using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using HealthApp.TestSupport; using ObservationService.Domain; using PatientProfileService.Domain; using Xunit; namespace Observation.AcceptanceTests; public sealed class ViewObservationContextTests(ObservationApiFixture fixture) : IClassFixture { private static int nextAccount = 180; private sealed record Saved(string AccountId, Guid PatientId, Guid ObservationId); private sealed record ContextData(string Setting, string ActivityCondition, decimal? RestDurationMinutes, string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances); private sealed record ObservationData(Guid ObservationId, Guid PatientId, DateTime MeasuredAt, int Systolic, int Diastolic, int Pulse, string? Context, string? Note, ContextData MeasurementContext); // Establish Given directly, independently of observation creation and its response. private async Task Seed(MeasurementContext? context = null, string? legacyText = null) { var account = "test-" + Interlocked.Increment(ref nextAccount); var patientId = Guid.NewGuid(); var observationId = Guid.NewGuid(); var timestamp = new DateTime(2026, 9, 12, 8, 0, 0); await using var patients = fixture.CreateDbContext(); patients.Patients.Add(new Patient { PatientId = patientId, AccountId = account, Name = "Retrieval patient", DateOfBirth = new DateOnly(1980, 1, 1), CreatedAt = timestamp, UpdatedAt = timestamp }); await patients.SaveChangesAsync(); await using var observations = fixture.CreateObservationDbContext(); observations.Observations.Add(new BloodPressureObservation { ObservationId = observationId, PatientId = patientId, MeasuredAt = timestamp, Systolic = 128, Diastolic = 82, Pulse = 68, Context = legacyText, Note = "Saved note", MeasurementContext = context ?? new(), CreatedAt = timestamp, UpdatedAt = timestamp }); await observations.SaveChangesAsync(); return new Saved(account, patientId, observationId); } private async Task Read(Guid observationId, string? token) { using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/observations/{observationId}"); if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); return await fixture.RawClient.SendAsync(request); } [Fact] public async Task Complete_saved_context_is_returned_with_its_measurements_and_timestamp_after_restart() { var saved = await Seed(new MeasurementContext { Setting = "Home", ActivityCondition = "AtRest", RestDurationMinutes = 5.5m, BodyPosition = "Seated", MeasuredArm = "Right", DeviceDetails = "Recorded device", CuffDetails = "Recorded cuff", AdditionalCircumstances = "Recorded circumstances" }, "Original context text"); await fixture.RestartHostsAsync(); var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, saved.AccountId); using var response = await Read(saved.ObservationId, token); Assert.Equal(HttpStatusCode.OK, response.StatusCode); var observation = (await response.Content.ReadFromJsonAsync())!; Assert.Equal(saved.ObservationId, observation.ObservationId); Assert.Equal(saved.PatientId, observation.PatientId); Assert.Equal(new DateTime(2026, 9, 12, 8, 0, 0), observation.MeasuredAt); Assert.Equal(128, observation.Systolic); Assert.Equal(82, observation.Diastolic); Assert.Equal(68, observation.Pulse); Assert.Equal("Original context text", observation.Context); Assert.Equal("Saved note", observation.Note); Assert.Equal(new ContextData("Home", "AtRest", 5.5m, "Seated", "Right", "Recorded device", "Recorded cuff", "Recorded circumstances"), observation.MeasurementContext); } [Fact] public async Task Partial_saved_context_distinguishes_known_setting_from_unknown_condition_and_details() { var saved = await Seed(new MeasurementContext { Setting = "Clinic" }); var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, saved.AccountId); using var response = await Read(saved.ObservationId, token); Assert.Equal(HttpStatusCode.OK, response.StatusCode); var observation = (await response.Content.ReadFromJsonAsync())!; Assert.Equal(new ContextData("Clinic", "Unknown", null, null, null, null, null, null), observation.MeasurementContext); Assert.Equal(saved.ObservationId, observation.ObservationId); } [Fact] public async Task Historical_free_text_is_returned_without_inventing_setting_or_activity() { var saved = await Seed(legacyText: "Morning reading"); var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, saved.AccountId); using var response = await Read(saved.ObservationId, token); Assert.Equal(HttpStatusCode.OK, response.StatusCode); var observation = (await response.Content.ReadFromJsonAsync())!; Assert.Equal("Morning reading", observation.Context); Assert.Equal("Saved note", observation.Note); Assert.Equal(new ContextData("Unknown", "Unknown", null, null, null, null, null, null), observation.MeasurementContext); } [Fact] public async Task Missing_observation_reports_not_found_without_disclosing_saved_context() { var saved = await Seed(new MeasurementContext { Setting = "Home" }); var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, saved.AccountId); using var response = await Read(Guid.NewGuid(), token); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Empty(await response.Content.ReadAsStringAsync()); } [Fact] public async Task Unauthorised_callers_cannot_read_observation_context() { var saved = await Seed(new MeasurementContext { Setting = "Home", DeviceDetails = "Private device details" }); var other = await Seed(); var otherToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, other.AccountId); var professional = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional-empty"); foreach (var (token, expected) in new[] { ((string?)null, HttpStatusCode.Unauthorized), ((string?)"invalid", HttpStatusCode.Unauthorized), ((string?)otherToken, HttpStatusCode.NotFound), ((string?)professional, HttpStatusCode.NotFound) }) { using var response = await Read(saved.ObservationId, token); Assert.Equal(expected, response.StatusCode); Assert.Empty(await response.Content.ReadAsStringAsync()); } } [Fact] public async Task Assigned_professional_reads_the_same_context_as_the_owner() { var saved = await Seed(new MeasurementContext { Setting = "Clinic", ActivityCondition = "AfterActivity", AdditionalCircumstances = "Actual circumstances" }, "Original narrative"); fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = saved.PatientId.ToString(); await fixture.RestartHostsAsync(); var patientToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, saved.AccountId); var professionalToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional"); using var patient = await Read(saved.ObservationId, patientToken); using var professional = await Read(saved.ObservationId, professionalToken); Assert.Equal(HttpStatusCode.OK, patient.StatusCode); Assert.Equal(HttpStatusCode.OK, professional.StatusCode); Assert.Equal(await patient.Content.ReadFromJsonAsync(), await professional.Content.ReadFromJsonAsync()); } }