using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Swashbuckle.AspNetCore.Annotations;

namespace AyaNova.Api.Controllers
{
    [ApiController]
    [ApiVersion("8.0")]
    [Route("api/v{version:apiVersion}/health")]
    [Produces("text/plain")]
    [Authorize]
    public class HealthController : ControllerBase
    {
        private readonly HealthCheckService _healthCheckService;
        public HealthController(HealthCheckService healthCheckService)
        {
            _healthCheckService = healthCheckService;
        }

        /// <summary>
        /// Get Health (verify server AND database connection)
        /// Note: for server monitoring or automation / orchestration use such as Docker prefer the mirror of this route at the server root: [api_server_url]/health 
        /// as it avoids API versioning issues
        /// i.e. Docker: HEALTHCHECK CMD curl --fail http://localhost:5000/health || exit
        /// </summary>
        /// <remarks>Provides an indication about the health of the API</remarks>
        /// <response code="200">API is healthy</response>
        /// <response code="503">API is unhealthy or in degraded state</response>
        [HttpGet]
        [AllowAnonymous]
        [ProducesResponseType(typeof(string), 200)]
        [SwaggerOperation(OperationId = "Health_Get")]
        public async Task<IActionResult> Get()
        {
            var report = await _healthCheckService.CheckHealthAsync();
            Response.Headers.Add("Cache-Control", "no-store, no-cache");
            return report.Status == HealthStatus.Healthy ? Ok(report.Status.ToString()) : StatusCode(503, report.Status.ToString());
        }
    }//eoc
}//eons