using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.EntityFrameworkCore;
using WerksverkaufScanner.Data;
using WerksverkaufScanner.Services;

var builder = WebApplication.CreateBuilder(args);

// --- WICHTIG FÜR IIS/REVERSE PROXY ---
// KEIN eigenes HTTPS/UseUrls setzen; TLS terminiert im IIS/Proxy.
// Falls du explizit klarstellen willst, dass IIS verwendet wird:
builder.WebHost.UseUrls("https://0.0.0.0:3300");
//builder.WebHost.UseIIS();

// 1) ConnectionString prüfen
var cs = builder.Configuration.GetConnectionString("Default");
if (string.IsNullOrWhiteSpace(cs))
    throw new InvalidOperationException("ConnectionStrings:Default fehlt oder ist leer.");

// 2) Framework-Services
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddControllers();          // AuthController (Login/Logout)
builder.Services.AddHttpClient();           // HTTP-Calls (optional)
builder.Services.AddHttpContextAccessor();  // wenn Services HttpContext brauchen

// 3) Auth/Authorization (Cookie)
builder.Services
    .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(o =>
    {
        o.LoginPath = "/login";
        o.AccessDeniedPath = "/login";
        o.ReturnUrlParameter = "returnUrl";
        o.SlidingExpiration = true;
        o.ExpireTimeSpan = TimeSpan.FromHours(15); // Auto-Logout nach 15h

        // Cookie-Härtung:
        o.Cookie.Name = "Werksverkauf.Auth";
        o.Cookie.HttpOnly = true;
        o.Cookie.SecurePolicy = CookieSecurePolicy.Always; // hinter IIS ok
        o.Cookie.SameSite = SameSiteMode.Lax;
    });
builder.Services.AddAuthorization();

// 4) App-Services & Datenzugriff
builder.Services.AddDbContextFactory<ScannerDb>(opt => opt.UseSqlServer(cs));
builder.Services.AddSingleton<StammdatenCache>();
builder.Services.AddScoped<InventurService>();
builder.Services.AddScoped<AuthService>();
builder.Services.AddScoped<PreisAenderungSqlService>();
builder.Services.AddScoped<IpFilialeService>(); // <— für IP→Filiale-Mapping
builder.Services.AddScoped<FilialService>();

// (Optional) Forwarded Headers – sinnvoll hinter IIS/Proxy
builder.Services.Configure<ForwardedHeadersOptions>(opt =>
{
    opt.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    // Falls du strikt nur bestimmte Proxys erlauben willst:
    // opt.KnownProxies.Add(IPAddress.Parse("10.0.0.1"));
});

var app = builder.Build();

// 5) Middleware-Pipeline
app.UseForwardedHeaders();   // vor HttpsRedirection/Authentication
app.UseHttpsRedirection();   // nutzt X-Forwarded-Proto hinter Proxy
app.UseStaticFiles();

app.UseRouting();

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

// 6) Endpoints
app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

// --- Nur für lokalen Start OHNE IIS, wenn du Kestrel direkt nutzen willst ---
// if (!app.Environment.IsProduction())
// {
//     app.Urls.Add("http://localhost:3300");
// }

app.Run();
