using Application;
using Application.Abstractions.Chat;
using Application.Abstractions.Crypto;
using Infrastructure;
using SharedKernel;
using System.Reflection;
using Web.Api;
using Web.Api.Extensions;
using Web.Api.Hubs;
using Web.Api.Services;

var builder = WebApplication.CreateBuilder(args);
var settings = builder.Configuration.Get<AppSettings>()!;

Console.Title = settings.App.Name;
Console.WriteLine($"ENV={builder.Environment.EnvironmentName}");
Console.WriteLine($"현재 시간: {DateTime.Now} / {TimeZoneInfo.Local.Id}");

builder.Services.Configure<AppSettings>(builder.Configuration);

builder.Services
    .AddApplication()
    .AddPresentation()
    .AddApiInfrastructure(builder.Configuration);

// CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy(settings.CorsPolicy.Name, policy =>
    {
        policy
            .WithOrigins(settings.CorsPolicy.AllowedOrigins.ToArray())
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials()
            .SetPreflightMaxAge(TimeSpan.FromSeconds(settings.CorsPolicy.PreflightMaxAgeSeconds));
    });
});

// SignalR
builder.Services.AddSignalR();
builder.Services.AddSingleton<ICryptoHubService, CryptoHubService>();

// Chat
builder.Services.AddSingleton<IChatHubService, ChatHubService>();
builder.Services.AddHostedService<KickSubscriberService>();

// Endpoints
builder.Services.AddEndpoints(Assembly.GetExecutingAssembly());
builder.Logging.AddConsole();

/**
 * =======================================================================================================================================================
 */

var app = builder.Build();

/**
 * =======================================================================================================================================================
 */

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// 상태 확인
app.MapHealthChecks("/health");

app.UseExceptionHandler();
app.UseCors(settings.CorsPolicy.Name);
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
app.MapEndpoints();
app.MapHub<CryptoHub>("/hubs/crypto");
app.MapHub<ChatHub>("/hubs/chat");

app.Run();