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

/// <summary>
/// Sepsis bundle compliance tracking: current bundle by encounter and bundle detail by id.
/// </summary>
[ApiController]
[Produces("application/json")]
[AuthorizePermission(ClinicalPermissions.EncountersRead)]
public class SepsisBundlesController : ControllerBase
{
    private readonly ISepsisBundleService _bundles;

    public SepsisBundlesController(ISepsisBundleService bundles) => _bundles = bundles;

    /// <summary>
    /// Lists sepsis bundles across all encounters with optional status filter.
    /// </summary>
    [HttpGet("api/v1/sepsis-bundles")]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
    public async Task<IActionResult> List(
        [FromQuery] string? status,
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20)
    {
        SepsisBundleComplianceStatus? parsed = status is not null
            ? SepsisBundleComplianceStatusExtensions.FromDbString(status)
            : null;

        var result = await _bundles.ListAsync(parsed, page, pageSize);
        return Ok(ApiResponse<object>.Ok(new
        {
            items = result.Items,
            page = result.Page,
            pageSize = result.PageSize,
            totalCount = result.TotalCount,
            totalPages = result.TotalPages
        }));
    }

    /// <summary>
    /// Returns the current (most recent) sepsis bundle for an encounter with elements and linked orders.
    /// </summary>
    /// <param name="encounterId">Encounter id.</param>
    [HttpGet("api/v1/encounters/{encounterId:guid}/sepsis-bundle/current")]
    [ProducesResponseType(typeof(ApiResponse<SepsisBundle>), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetCurrentByEncounter(Guid encounterId)
    {
        var bundle = await _bundles.GetCurrentByEncounterAsync(encounterId);
        if (bundle is null)
            return Ok(ApiResponse<SepsisBundle?>.Ok(null));

        return Ok(ApiResponse<SepsisBundle>.Ok(bundle));
    }

    /// <summary>
    /// Returns a sepsis bundle by id with all elements and linked orders.
    /// </summary>
    /// <param name="id">Bundle id.</param>
    [HttpGet("api/v1/sepsis-bundles/{id:guid}")]
    [ProducesResponseType(typeof(ApiResponse<SepsisBundle>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetById(Guid id)
    {
        var bundle = await _bundles.GetByIdAsync(id);
        return Ok(ApiResponse<SepsisBundle>.Ok(bundle));
    }
}
