using InsightsService.Domain; using InsightsService.Application; using InsightsService.Contracts; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace InsightsService.Controllers; [ApiController] [Route("api/patients/{patientId:guid}/insights")] public sealed class InsightsController(InsightsApplicationService service) : ControllerBase { [HttpGet] public async Task> GetSummary(Guid patientId, [FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to, [FromQuery] ContextSelection selection, CancellationToken cancellationToken) { try { var insight = await service.GetSummaryAsync(patientId, from, to, selection, cancellationToken); return insight is null ? Problem(statusCode: StatusCodes.Status404NotFound, title: "Insufficient observation data for calculation.") : Ok(new HealthInsightDto(insight.PatientId, insight.PeriodStart, insight.PeriodEnd, insight.AverageSystolic, insight.AverageDiastolic, insight.AveragePulse, insight.MinSystolic, insight.MaxSystolic, insight.MinDiastolic, insight.MaxDiastolic, insight.AppliedSelection, insight.ContributingCount, insight.ContextExplanation)); } catch (ArgumentException) { ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time."); return ValidationProblem(ModelState); } catch (HttpRequestException) { return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history is unavailable."); } catch (System.Text.Json.JsonException) { return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history response is invalid."); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Observation history timed out."); } } [HttpGet("/api/patients/{patientId:guid}/trends")] public async Task> GetTrend(Guid patientId, [FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to, [FromQuery] ContextSelection selection, CancellationToken cancellationToken) { try { return Ok(await service.GetTrendAsync(patientId, from, to, selection, cancellationToken)); } catch (ArgumentException) { ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time."); return ValidationProblem(ModelState); } catch (HttpRequestException) { return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history is unavailable."); } catch (System.Text.Json.JsonException) { return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history response is invalid."); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Observation history timed out."); } } }