using AiLogia.Web.Data;
using AiLogia.Web.Infrastructure;
using AiLogia.Web.Services;

namespace AiLogia.Web;

public sealed class BotOptions
{
    public string Username { get; init; } = "";
}

internal class Program
{
    private static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // MVC-пайплайн
        builder.Services.AddControllersWithViews();
        builder.Services.AddHttpContextAccessor();

        RegisterServices(builder);

        // Красивые URL
        builder.Services.AddRouting(o =>
        {
            o.LowercaseUrls = true;
            o.LowercaseQueryStrings = true;
            o.AppendTrailingSlash = false; // если хочешь слэши на конце — поставь true
        });

        // добавим config.json в конфигурацию
        builder.Configuration
            .AddJsonFile("config.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables();

        builder.Services.Configure<BotOptions>(
            builder.Configuration.GetSection("LinkedBot"));

        builder.WebHost.ConfigureKestrel(options =>
        {
            // настройки будут подхвачены из "Kestrel" раздела в config.json
            options.Configure(builder.Configuration.GetSection("Kestrel"));
        });

        // Cookie-сессия
        builder.Services
            .AddAuthentication(options =>
            {
                options.DefaultScheme = "AppCookie";
                options.DefaultChallengeScheme = "AppCookie";
            })
            .AddCookie("AppCookie", opts =>
            {
                opts.LoginPath = "/auth/login";
                opts.LogoutPath = "/auth/logout";
                opts.AccessDeniedPath = "/auth/denied";
                opts.Cookie.Name = builder.Configuration.GetSection("Auth")["CookieName"];      // на проде: HTTPS + без Domain
                opts.Cookie.HttpOnly = true;
                //                opts.Cookie.SecurePolicy = CookieSecurePolicy.Always; // на проде: Always
                opts.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                opts.Cookie.SameSite = SameSiteMode.Lax;
                opts.Cookie.IsEssential = true;
                opts.SlidingExpiration = true;
                opts.ExpireTimeSpan = TimeSpan.FromDays(1);
            });


        builder.Services.AddAuthorization();

        // HttpClient к Auth-микросервису
        builder.Services.AddHttpClient("AuthMs", (sp, c) =>
        {
            var cfg = sp.GetRequiredService<IConfiguration>();
            var baseUrl = cfg["AuthService:BaseUrl"] ?? throw new InvalidOperationException("AuthService:BaseUrl not set");
            c.BaseAddress = new Uri(baseUrl);
        });

        // наш мини-клиент для consume
        builder.Services.AddScoped<IAuthLinksClient, AuthLinksClient>();


        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (!app.Environment.IsDevelopment())
        {
            app.UseExceptionHandler("/Home/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.UseStaticFiles();
        app.UseRouting();

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

        // Публичные эндпоинты авторизации — без требований к входу
        app.MapControllerRoute(
            name: "auth",
            pattern: "auth/{action=login}/{id?}",
            defaults: new { controller = "Auth" }
        ).AllowAnonymous();

        app.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");

        app.Run();
    }

    private static void RegisterServices(WebApplicationBuilder builder)
    {
        // auth
        builder.Services.AddScoped<ICurrentUser, CurrentUser>();
        builder.Services.AddScoped<IAuthLinksClient, AuthLinksClient>();

        // data
        builder.Services.AddSingleton<IRecommendationsRepository, RecommendationsRepository>();
        builder.Services.AddSingleton<ITestsRepository, TestsRepository>();

        builder.Services.AddHttpClient();
        builder.Services.AddSingleton<IAssistantProxyClient, AssistantProxyClient>();


        // account ->

        // account -> tests
        builder.Services.AddSingleton<ITestsService, TestsService>();
        // account -> tests results
        builder.Services.AddSingleton<IMeService, MeService>();
        // account -> recommendations
        builder.Services.AddSingleton<IRecommendationsService, RecommendationsService>();
        // account -> cources
        builder.Services.AddSingleton<ICoursesService, CoursesService>();
    }
}