using Microsoft.Extensions.Hosting.WindowsServices;
using Serilog;
using SharedKernel;
using Admin.Extensions;
using Admin.Pages.Shared.Layout;
using Admin.Middlewares;
using Application;
using Infrastructure;

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/admin-.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();
}

// Add services to the container.
var mvcBuilder = builder.Services.AddRazorPages(options =>
{
    options.Conventions.AuthorizeFolder("/");
    options.Conventions.AllowAnonymousToAreaFolder("Identity", "/Account");
});

// 프로그램 설정 값 배치
builder.Services.Configure<AppSettings>(builder.Configuration);

// DB 연결
builder.Services.AddApplication().AddAdminInfrastructure(builder.Configuration);

// 관리자 레이아웃
builder.Services.AddScoped<ILayoutDataProvider, LayoutDataProvider>();

// 인증 및 권한 부여
builder.Services.AddAdminForwardedHeaders(settings); // 리버스 프록시 및 접근 제어
builder.Services.AddAdminIdentity(settings); // 관리자단 Identity 인증 및 비밀번호 정책

builder.Logging.AddConsole(); // 터미널에 로그 출력

if (builder.Environment.IsDevelopment())
{
    builder.Logging.AddDebug(); // 디버깅 창에 로그 출력
}

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

var app = builder.Build();

// 초기 관리자 계정 시드
await app.SeedAdminAccountAsync();

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

// 환경변수 불러오기
var env = Environment.GetEnvironmentVariable("environmentVariables");


app.Use(async (context, next) =>
{
    context.Items["env"] = env; // 환경변수를 static 변수로 저장
    await next();
});

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

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

// 메뉴 기반 역할 권한 체크
app.UseMiddleware<MenuAuthorizationMiddleware>();

// 관리자 접속 기록
app.UseMiddleware<AdminAccessLogMiddleware>();

app.MapStaticAssets();
app.MapRazorPages().WithStaticAssets();

app.Run();
