using Microsoft.AspNetCore.Mvc;
using Nostr.Client.Json;
using Nostr.Client.Messages;
using NostrServices.Client;
using NostrServices.Services;

namespace NostrServices.Controllers;

[Route("/api/v1/export")]
public class ExportController : Controller
{
    private readonly RedisStore _store;

    public ExportController(RedisStore store)
    {
        _store = store;
    }

    /// <summary>
    /// Get cached profile data
    /// </summary>
    /// <param name="id">The pubkey of the user</param>
    /// <returns></returns>
    [HttpGet("profile/{id}")]
    [Produces("application/json", Type = typeof(CompactProfile))]
    public async Task<IActionResult> GetProfile([FromRoute] string id)
    {
        var nid = await Extensions.TryParseIdentifier(id);
        if (nid != default)
        {
            if (nid.Hrp is "npub" or "nprofile")
            {
                var px = await _store.GetProfile(nid.Special);
                if (px != default)
                {
                    return Content(NostrJson.Serialize(px)!, "application/json");
                }

                return NotFound();
            }
        }

        return BadRequest();
    }

    /// <summary>
    /// Get cached event
    /// </summary>
    /// <param name="id">note1/nevent/naddr</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    [Produces("application/json", Type = typeof(NostrEvent))]
    public async Task<IActionResult> GetEvent([FromRoute] string id)
    {
        var nid = await Extensions.TryParseIdentifier(id);
        if (nid != default)
        {
            if (nid.Hrp is "nevent" or "note" or "naddr")
            {
                var ex = await _store.GetEvent(nid);
                if (ex != default)
                {
                    return Content(NostrJson.Serialize(ex.ToNostrEvent())!, "application/json");
                }

                return NotFound();
            }
        }

        return BadRequest();
    }
}
