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

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

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

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

        return Ok(encounter);
    }

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