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

[ApiController]
[Route("api/v1/encounters/{encounterId:guid}/observations")]
[Authorize]
public class ObservationsController : ControllerBase
{
    private readonly ILocalObservationService _observations;
    private readonly IObservationQueryService _query;

    public ObservationsController(
        ILocalObservationService observations,
        IObservationQueryService query)
    {
        _observations = observations;
        _query = query;
    }

    [HttpPost]
    public async Task<IActionResult> Ingest(Guid encounterId, [FromBody] IngestObservationRequest req)
    {
        var result = await _observations.IngestAsync(encounterId, req);
        if (result.IsDuplicate)
            return Ok(ApiResponse<object>.Ok(new { duplicate = true, result.Observation }));
        return StatusCode(201, ApiResponse<object>.Created(new
        {
            observation = result.Observation,
            alert = result.Alert
        }));
    }

    [HttpGet]
    public async Task<IActionResult> History(
        Guid encounterId,
        [FromQuery] string? code,
        [FromQuery] DateTimeOffset? from,
        [FromQuery] DateTimeOffset? to,
        [FromQuery] int limit = 20,
        [FromQuery] string? cursor = null)
    {
        var page = await _query.GetHistoryAsync(encounterId, code, from, to, limit, cursor);
        return Ok(ApiResponse<object>.Ok(new
        {
            items = page.Items,
            nextCursor = page.NextCursor,
            hasMore = page.HasMore
        }));
    }
}
