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, CancellationToken cancellationToken) { try { var insight = await service.GetSummaryAsync(patientId, from, to, 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)); } 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."); } } }