using Microsoft.AspNetCore.Mvc;

namespace DeepDrftPublic.Controllers;

/// <summary>
/// Proxies the public stats read surface to DeepDrftAPI so the browser never makes a cross-origin
/// request. Mirrors <see cref="ReleaseProxyController"/>: the WASM client issues relative
/// <c>api/stats/*</c> requests against this host, which forwards them upstream. SSR prerender calls
/// DeepDrftAPI directly via the same named client — no proxy hop on the server side. Unauthenticated read.
/// </summary>
[ApiController]
[Route("api/stats")]
public class StatsProxyController : ControllerBase
{
    private readonly HttpClient _upstream;
    private readonly ILogger<StatsProxyController> _logger;

    public StatsProxyController(IHttpClientFactory httpClientFactory, ILogger<StatsProxyController> logger)
    {
        _upstream = httpClientFactory.CreateClient("DeepDrft.API");
        _logger = logger;
    }

    /// <summary>Proxies the home hero aggregate figures. Small JSON, buffered and relayed.</summary>
    [HttpGet("home")]
    public async Task<ActionResult> GetHome(CancellationToken ct = default)
    {
        HttpResponseMessage upstream;
        try
        {
            upstream = await _upstream.GetAsync("api/stats/home", HttpCompletionOption.ResponseHeadersRead, ct);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Upstream call to DeepDrftAPI stats/home failed");
            return StatusCode(502, "Upstream unavailable");
        }

        using (upstream)
        {
            if (!upstream.IsSuccessStatusCode)
            {
                _logger.LogWarning("DeepDrftAPI stats/home returned {Status}", (int)upstream.StatusCode);
                return StatusCode((int)upstream.StatusCode);
            }

            var json = await upstream.Content.ReadAsStringAsync(ct);
            return Content(json, "application/json");
        }
    }
}
