using Microsoft.AspNetCore.Mvc;

namespace ReAct_PME.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class StatusController : ControllerBase
    {
        private readonly IWebHostEnvironment _env;
        private readonly IConfiguration _config;

        public StatusController(IWebHostEnvironment env, IConfiguration config)
        {
            _env = env;
            _config = config;
        }

        [HttpGet]
        public IActionResult GetStatus()
        {
            try
            {
                var corsOrigins = _config.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();

                var configSources = _config
                    .AsEnumerable()
                    .Select(kvp => kvp.Key)
                    .Distinct()
                    .OrderBy(k => k)
                    .ToList();

                var result = new
                {
                    Environment = _env.EnvironmentName,
                    CorsOrigins = corsOrigins,
                    Jwt = new
                    {
                        Issuer = _config["Jwt:Issuer"],
                        Audience = _config["Jwt:Audience"],
                        ExpireMinutes = _config["Jwt:ExpireMinutes"],
                        KeyDefined = !string.IsNullOrWhiteSpace(_config["Jwt:SecretKey"])
                    },
                    ConnectionStringDefined = !string.IsNullOrWhiteSpace(_config.GetConnectionString("DefaultConnection")),
                    ConfigKeysLoaded = configSources,
                    AspNetCoreEnv = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
                };

                return Ok(result);
            }

            catch (Exception ex)
            {
                return StatusCode(500, new { error = ex.Message });
            }
        }
    }
}
                
