using Application;
using Application.Abstractions.Chat;
using Infrastructure;
using SharedKernel;
using System.Reflection;
using Microsoft.Extensions.Hosting.WindowsServices;
using Serilog;
using Web.Api;
using Web.Api.Extensions;
using Web.Api.Hubs;
using Web.Api.Services;
using Infrastructure.Hubs;

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

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

builder.Host.UseWindowsService();

// Serilog — Production에서만 파일 로그
if (builder.Environment.IsProduction())
{
    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(builder.Configuration)
        .WriteTo.File("logs/webapi-.log",
            rollingInterval: RollingInterval.Day,
            retainedFileCountLimit: 30,
            outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
        .CreateLogger();
    builder.Host.UseSerilog();
}

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();

// 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<ChatHub>("/hubs/chat");
app.MapHub<AppHub>("/hubs/app");
app.MapHub<DonationHub>("/hubs/donation");

// 서버 시작 시 이전 채팅 접속자 정보 초기화 (stale 연결 제거)
using (var scope = app.Services.CreateScope())
{
    await scope.ServiceProvider.GetRequiredService<IChatConnectionTracker>().ClearAllAsync();
}

app.Run();