using SharedKernel;
using Admin.Extensions;
using Admin.Pages.Shared.Layout;
using Application;
using Infrastructure;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

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

Console.Title = settings.App.Name;
Console.WriteLine($"ENV={builder.Environment.EnvironmentName}");
Console.WriteLine(TimeZoneInfo.Local.Id);
Console.WriteLine(DateTime.Now);
Console.WriteLine(DateTime.UtcNow);

// Add services to the container.
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();

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

// 환경변수 불러오기
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.MapStaticAssets();
app.MapRazorPages().WithStaticAssets();

app.Run();
