using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NexusIdentity.Api.Services;

namespace NexusIdentity.Api.Controllers;

[ApiController]
[Route("api/downloads")]
public sealed class DownloadsController : ControllerBase
{
    private readonly DownloadManifestService _manifestService;

    public DownloadsController(DownloadManifestService manifestService)
    {
        _manifestService = manifestService;
    }

    [AllowAnonymous]
    [HttpGet("latest")]
    public async Task<IActionResult> GetLatest(CancellationToken ct)
    {
        var manifest = await _manifestService.GetLatestManifestAsync(ct);
        if (manifest is null)
        {
            return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "manifest_unavailable" });
        }

        return Content(manifest.RootElement.GetRawText(), "application/json");
    }

    [AllowAnonymous]
    [HttpGet]
    public async Task<IActionResult> List(CancellationToken ct)
    {
        var manifest = await _manifestService.GetLatestManifestAsync(ct);
        if (manifest is null)
        {
            return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "manifest_unavailable" });
        }

        var root = manifest.RootElement;
        var entry = new Dictionary<string, object?>();
        foreach (var property in root.EnumerateObject())
        {
            entry[property.Name] = JsonSerializer.Deserialize<object>(property.Value.GetRawText());
        }

        return Ok(new[] { entry });
    }
}
