using System.Net.WebSockets;
using FASTERlay;
using Newtonsoft.Json;
using Nostr.Client.Json;
using NostrRelay;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<NostrStore>(svc =>
{
    var logger = svc.GetRequiredService<ILogger<NostrStore>>();
    return new NostrStore("./data", logger);
});

builder.Services.AddTransient<FasterRelay>();

var app = builder.Build();


app.UseWebSockets();
app.MapGet("/", async ctx =>
{
    if (ctx.WebSockets.IsWebSocketRequest)
    {
        var logger = app.Services.GetRequiredService<ILogger<NostrRelay<FasterRelay>>>();
        using var handler = app.Services.GetRequiredService<FasterRelay>();
        try
        {
            var ws = await ctx.WebSockets.AcceptWebSocketAsync();
            var wsCtx = new NostrClientContext(ws, ctx.Connection.RemoteIpAddress!,
                ctx.Request.Headers.UserAgent.FirstOrDefault() ?? string.Empty);

            var nostrRelay = new NostrRelay<FasterRelay>(handler, wsCtx, ctx.RequestAborted, logger);

            await nostrRelay.Read();

            await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, null, ctx.RequestAborted);
        }
        catch (Exception ex)
        {
            logger.LogDebug(ex.Message);
        }
    }
    else
    {
        var isRelayDocRequest = ctx.Request.Headers.Accept.FirstOrDefault()
            ?.Equals("application/nostr+json", StringComparison.InvariantCultureIgnoreCase) ?? false;

        if (isRelayDocRequest)
        {
            var doc = new RelayDocument
            {
                Name = "",
                Description = "C# FASTER relay",
                Pubkey = "63fe6318dc58583cfe16810f86dd09e18bfd76aabc24a0081ce2856f330504ed",
                SupportedNips = [1],
                Software = "NostrServices",
                Icon = "https://void.cat/d/CtXsF5EvqNLG3K85TgezCt.webp",
                Limitation = new()
                {
                    RestrictedWrites = false,
                    AuthRequired = false,
                    PaymentRequired = false
                }
            };

            ctx.Response.ContentType = "application/json";
            await ctx.Response.WriteAsync(JsonConvert.SerializeObject(doc, NostrSerializer.Settings));
        }
        else
        {
            await ctx.Response.WriteAsync("Hey");
        }
    }
});

app.Run();
