using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("fhir/Observation")]
[Produces("application/fhir+json")]
[Authorize]
public class FhirObservationController : ControllerBase
{
    private readonly IFhirService _fhir;

    public FhirObservationController(IFhirService fhir) => _fhir = fhir;

    /// <summary>
    /// FHIR read: GET /fhir/Observation/{id}
    /// </summary>
    [HttpGet("{id}")]
    public async Task<IActionResult> Read(string id)
    {
        var observation = await _fhir.GetObservationAsync(Guid.Parse(id));
        if (observation is null)
            return NotFound(FhirErrorHelper.NotFound("Observation", id));

        return Ok(observation);
    }

    /// <summary>
    /// FHIR search: GET /fhir/Observation?patient=X&amp;code=Y&amp;date=Z&amp;category=W
    /// Supports search by patient reference, LOINC code, date range, and category.
    /// </summary>
    [HttpGet]
    public async Task<IActionResult> Search(
        [FromQuery] string? patient,
        [FromQuery] string? code,
        [FromQuery] string? date,
        [FromQuery] string? category,
        [FromQuery] string? encounter,
        [FromQuery(Name = "_count")] int count = 50,
        [FromQuery(Name = "_offset")] int offset = 0)
    {
        var bundle = await _fhir.SearchObservationsAsync(
            patient, code, date, category, encounter, count, offset);
        return Ok(bundle);
    }
}