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

/// <summary>
/// Gateway fleet operations: fleet listing, gateway detail, and site summaries.
/// </summary>
[ApiController]
[Route("api/v1/operations")]
[Authorize]
[Produces("application/json")]
public class OperationsController : ControllerBase
{
    private readonly IOperationsService _operations;

    public OperationsController(IOperationsService operations) => _operations = operations;

    /// <summary>
    /// Lists registered gateways with optional status and site filters.
    /// </summary>
    /// <param name="status">Optional gateway status filter (DB literal, e.g. DEGRADED).</param>
    /// <param name="siteId">Optional site id filter.</param>
    /// <returns>Gateway fleet items.</returns>
    [HttpGet("gateways")]
    [AuthorizePermission(ClinicalPermissions.UsersAdmin)]
    [ProducesResponseType(typeof(ApiResponse<IReadOnlyList<GatewayFleetItem>>), StatusCodes.Status200OK)]
    public async Task<IActionResult> ListGateways(
        [FromQuery] string? status,
        [FromQuery] Guid? siteId,
        CancellationToken ct)
    {
        var items = await _operations.GetGatewayFleetAsync(
            new GatewayFleetFilter(status, siteId), ct);
        return Ok(ApiResponse<IReadOnlyList<GatewayFleetItem>>.Ok(items));
    }

    /// <summary>
    /// Gets a single gateway by id with buffer depth, heartbeat metadata, and sync history.
    /// </summary>
    /// <param name="gatewayId">Gateway id.</param>
    /// <returns>Gateway detail.</returns>
    [HttpGet("gateways/{gatewayId:guid}")]
    [AuthorizePermission(ClinicalPermissions.UsersAdmin)]
    [ProducesResponseType(typeof(ApiResponse<GatewayDetailResponse>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetGateway(Guid gatewayId, CancellationToken ct)
    {
        var detail = await _operations.GetGatewayDetailAsync(gatewayId, ct);
        return Ok(ApiResponse<GatewayDetailResponse>.Ok(detail));
    }

    /// <summary>
    /// Returns an aggregate gateway summary for a site.
    /// </summary>
    /// <param name="siteId">Site id.</param>
    /// <returns>Site gateway summary.</returns>
    [HttpGet("sites/{siteId:guid}/summary")]
    [AuthorizePermission(ClinicalPermissions.UsersAdmin)]
    [ProducesResponseType(typeof(ApiResponse<SiteGatewaySummaryResponse>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetSiteSummary(Guid siteId, CancellationToken ct)
    {
        var summary = await _operations.GetSiteSummaryAsync(siteId, ct);
        return Ok(ApiResponse<SiteGatewaySummaryResponse>.Ok(summary));
    }
}