using RelayServer.Endpoints;
using RelayServer.Services.Chat;
using RelayServer.Services.Core;
using RelayServer.Services.Data;
using RelayServer.Services.Rtc;
using RelayShared.Rtc;
using RelayShared.Services;
using WebSocketSharp.Server;

var surrealService = new SurrealService();
var coreClient = new CoreClientService();
var cryptoService = new ChannelCryptoService();

await using var db = await surrealService.ConnectAsync();

ChatSocketBehavior.ClientKeyService = new ClientKeyService(db);
ChatSocketBehavior.Db = db;
ChatSocketBehavior.ChannelCryptoService = cryptoService;

var bootstrapService = new ServerBootstrapService(db, coreClient, cryptoService);
await bootstrapService.InitializeAsync();

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton(db);
builder.Services.AddScoped<RtcCallService>();

var app = builder.Build();

app.MapGet("/", () => "Server Running!");
app.MapRtcEndpoints();

var wssv = new WebSocketServer("ws://localhost:1337");
wssv.AddWebSocketService<ChatSocketBehavior>("/");
RtcNotificationService.Server = wssv;

wssv.Start();
Console.WriteLine("WebSocket server started");

await app.StartAsync();
Console.WriteLine("HTTP API started");

ConsoleCommandService.Start();
await Task.Delay(Timeout.Infinite, ConsoleCommandService.ShutdownTokenSource.Token);

wssv.Stop();
await app.StopAsync();
return;