using System.Text;
using System.Text.Json;
using System.Security.Claims;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Extensions.Logging.Abstractions;
using ROLAC.API.Data;
using ROLAC.API.Data.Interceptors;
using ROLAC.API.Data.Logging;
using ROLAC.API.Entities;
using ROLAC.API.Json;
using ROLAC.API.Middleware;
using ROLAC.API.Services;
using ROLAC.API.Services.Logging;
using ROLAC.API.Services.Security;

var builder = WebApplication.CreateBuilder(args);
var config  = builder.Configuration;

// ---------------------------------------------------------------------------
// Database
// ---------------------------------------------------------------------------
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<CurrentUserAccessor>();
builder.Services.AddScoped<AuditSaveChangesInterceptor>();
builder.Services.AddScoped<AuditLogInterceptor>();
builder.Services.AddDbContext<AppDbContext>((sp, opt) =>
    opt.UseNpgsql(config.GetConnectionString("DefaultConnection"))
       .AddInterceptors(
           sp.GetRequiredService<AuditSaveChangesInterceptor>(),
           sp.GetRequiredService<AuditLogInterceptor>()));

// Dedicated context for log writes — NO interceptors and a silent logger factory, so persisting
// a log row produces no log events the DB sink would pick up (breaks recursion / log-storms).
builder.Services.AddDbContext<LogDbContext>(opt =>
    opt.UseNpgsql(config.GetConnectionString("DefaultConnection"))
       .UseLoggerFactory(NullLoggerFactory.Instance));

// ---------------------------------------------------------------------------
// System + audit logging (custom EF DB sink)
// ---------------------------------------------------------------------------
builder.Services.Configure<DatabaseLoggerOptions>(config.GetSection("Logging:Database"));
builder.Services.AddSingleton<SystemLogQueue>();
builder.Services.AddSingleton<ILoggerProvider, DbLoggerProvider>();
builder.Services.AddHostedService<LogWriterBackgroundService>();
builder.Services.AddScoped<IAuditLogger, AuditLogger>();
builder.Services.AddScoped<ISystemLogQueryService, SystemLogQueryService>();
builder.Services.AddScoped<IAuditLogQueryService, AuditLogQueryService>();

// ---------------------------------------------------------------------------
// Identity (API-only — no cookie auth; JWT is the default scheme)
// ---------------------------------------------------------------------------
builder.Services
    .AddIdentityCore<AppUser>(opt =>
    {
        opt.Password.RequiredLength         = 8;
        opt.Password.RequireDigit           = true;
        opt.Password.RequireUppercase       = true;
        opt.Password.RequireLowercase       = true;
        opt.Password.RequireNonAlphanumeric = true;
        opt.User.RequireUniqueEmail         = true;
    })
    .AddRoles<AppRole>()
    .AddEntityFrameworkStores<AppDbContext>()
    .AddDefaultTokenProviders();

// ---------------------------------------------------------------------------
// JWT Authentication
// ---------------------------------------------------------------------------
var jwtKey = config["Jwt:SecretKey"]
    ?? throw new InvalidOperationException("Jwt:SecretKey is not configured.");

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(opt =>
    {
        // Keep JWT claim names exactly as written ("role", "sub", "email").
        // Without this, .NET 8's JsonWebTokenHandler may remap "role" to the
        // long ClaimTypes.Role URI, which conflicts with RoleClaimType = "role".
        opt.MapInboundClaims = false;

        opt.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer           = true,
            ValidateAudience         = true,
            ValidateLifetime         = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer              = config["Jwt:Issuer"],
            ValidAudience            = config["Jwt:Audience"],
            IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
            NameClaimType            = "sub",
            RoleClaimType            = "role",
            ClockSkew                = TimeSpan.FromMinutes(1),
        };

        // Diagnostic events — visible in the API console while debugging 401s.
        opt.Events = new JwtBearerEvents
        {
            OnAuthenticationFailed = ctx =>
            {
                Console.WriteLine(
                    $"[JWT] Auth failed: {ctx.Exception.GetType().Name} — {ctx.Exception.Message}");
                return Task.CompletedTask;
            },
            OnChallenge = ctx =>
            {
                // Fires when a 401 challenge is about to be sent.
                Console.WriteLine(
                    $"[JWT] Challenge: error={ctx.Error}, description={ctx.ErrorDescription}");
                return Task.CompletedTask;
            },
            OnForbidden = ctx =>
            {
                // Fires when user IS authenticated but lacks the required role (403).
                Console.WriteLine(
                    $"[JWT] Forbidden: user={ctx.HttpContext.User.Identity?.Name}, " +
                    $"roles=[{string.Join(',', ctx.HttpContext.User.Claims
                        .Where(c => c.Type == "role")
                        .Select(c => c.Value))}]");
                return Task.CompletedTask;
            },
        };
    });

// ---------------------------------------------------------------------------
// CORS
// ---------------------------------------------------------------------------
var allowedOrigins = config.GetSection("Cors:AllowedOrigins").Get<string[]>()
    ?? ["http://localhost:4200"];

builder.Services.AddCors(opt =>
    opt.AddPolicy("Angular", policy =>
        policy.WithOrigins(allowedOrigins)
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials()));

// ---------------------------------------------------------------------------
// Application services
// ---------------------------------------------------------------------------
builder.Services.AddScoped<ITokenService,          TokenService>();
builder.Services.AddScoped<IAuthService,           AuthService>();
builder.Services.AddScoped<IMemberService,         MemberService>();
builder.Services.AddScoped<IUserManagementService, UserManagementService>();
builder.Services.AddScoped<IInvitationService,     InvitationService>();
builder.Services.AddScoped<IGivingCategoryService, GivingCategoryService>();
builder.Services.AddScoped<IGivingService, GivingService>();
builder.Services.AddScoped<IOfferingSessionService, OfferingSessionService>();
builder.Services.AddScoped<IMinistryService, MinistryService>();
builder.Services.AddScoped<ROLAC.API.Services.Storage.IFileStorage,
                           ROLAC.API.Services.Storage.LocalDiskFileStorage>();
builder.Services.AddScoped<IExpenseCategoryService, ExpenseCategoryService>();
builder.Services.AddScoped<IExpenseService, ExpenseService>();
builder.Services.AddScoped<IExpenseSnapshotService, ExpenseSnapshotService>();
builder.Services.AddScoped<IMonthlyStatementService, MonthlyStatementService>();
builder.Services.AddScoped<IFinanceDashboardService, FinanceDashboardService>();
builder.Services.AddScoped<IForm990ReportService, Form990ReportService>();
builder.Services.AddScoped<IForm1099ReportService, Form1099ReportService>();
builder.Services.AddScoped<IPayee1099Service, Payee1099Service>();
builder.Services.AddScoped<I1099FormService, Form1099FormService>();
builder.Services.AddDataProtection();
builder.Services.AddScoped<ITinProtector, TinProtector>();
builder.Services.AddScoped<IChurchProfileService, ChurchProfileService>();
builder.Services.AddScoped<ISettingsService, SettingsService>();
builder.Services.AddScoped<IDisbursementService, DisbursementService>();
builder.Services.AddScoped<ROLAC.API.Services.Disbursement.ICheckPrintService,
                           ROLAC.API.Services.Disbursement.CheckPrintService>();
// Pre-printed check-stock field coordinates; tune in appsettings.json without recompiling.
builder.Services.Configure<ROLAC.API.Services.Disbursement.CheckPrintLayoutOptions>(
    config.GetSection("CheckPrint:Layout"));
builder.Services.AddScoped<IMealAttendanceService, MealAttendanceService>();

// ── Notifications (email via SMTP + Line) ──────────────────────────────────
// IOptions binding stays only as the one-time seed/fallback; the runtime source of truth is the
// DB-backed NotificationSetting row, read (and hot-reloaded) via INotificationSettingsService.
builder.Services.Configure<ROLAC.API.Services.Notifications.SmtpOptions>(config.GetSection("Smtp"));
builder.Services.Configure<ROLAC.API.Services.Notifications.LineOptions>(config.GetSection("Line"));
builder.Services.AddSingleton<ROLAC.API.Services.Notifications.INotificationSettingsService,
                              ROLAC.API.Services.Notifications.NotificationSettingsService>();
builder.Services.AddScoped<ROLAC.API.Services.Notifications.ISmtpDispatcher,
                           ROLAC.API.Services.Notifications.MailKitSmtpDispatcher>();
builder.Services.AddScoped<ROLAC.API.Services.Notifications.IEmailService,
                           ROLAC.API.Services.Notifications.EmailService>();
builder.Services.AddScoped<ROLAC.API.Services.Notifications.ILineNotificationService,
                           ROLAC.API.Services.Notifications.LineNotificationService>();
builder.Services.AddHttpClient<ROLAC.API.Services.Notifications.IMessageChannel,
                               ROLAC.API.Services.Notifications.LineMessageChannel>();
builder.Services.AddScoped<ROLAC.API.Services.Notifications.IWebPushSender,
                           ROLAC.API.Services.Notifications.WebPushSender>();
builder.Services.AddScoped<ROLAC.API.Services.Notifications.IWebPushService,
                           ROLAC.API.Services.Notifications.WebPushService>();

// ── AI assist (expense translation + category suggestion) ──────────────────
// Backend proxy so the API key stays server-side. Provider + model + key come from the
// ChurchProfile DB record (editable via Church Profile → AI 設定); the factory picks Claude
// or Gemini per request based on ChurchProfile.AiProvider.
builder.Services.AddHttpClient<ROLAC.API.Services.Ai.GeminiExpenseAiService>();
builder.Services.AddHttpClient<ROLAC.API.Services.Ai.ClaudeExpenseAiService>();
builder.Services.AddScoped<ROLAC.API.Services.Ai.IChurchAiConfigProvider,
                           ROLAC.API.Services.Ai.ChurchAiConfigProvider>();
builder.Services.AddScoped<ROLAC.API.Services.Ai.IExpenseAiServiceFactory,
                           ROLAC.API.Services.Ai.ExpenseAiServiceFactory>();

// Category-mapping AI (define a 大項/小項: refine name + translate + suggest Form 990 line).
builder.Services.AddHttpClient<ROLAC.API.Services.Ai.GeminiExpenseCategoryAiService>();
builder.Services.AddHttpClient<ROLAC.API.Services.Ai.ClaudeExpenseCategoryAiService>();
builder.Services.AddScoped<ROLAC.API.Services.Ai.IExpenseCategoryAiServiceFactory,
                           ROLAC.API.Services.Ai.ExpenseCategoryAiServiceFactory>();

// ---------------------------------------------------------------------------
// Configurable role-based permissions (RBAC matrix)
// ---------------------------------------------------------------------------
builder.Services.AddMemoryCache();
builder.Services.AddSingleton<IPermissionService, PermissionService>();
builder.Services.AddAuthorization();
// Dynamic policy provider materializes "PERM:<module>:<action>" policies on demand;
// must be registered AFTER AddAuthorization so it overrides the default provider.
builder.Services.AddSingleton<Microsoft.AspNetCore.Authorization.IAuthorizationPolicyProvider,
                              ROLAC.API.Authorization.PermissionPolicyProvider>();
builder.Services.AddScoped<Microsoft.AspNetCore.Authorization.IAuthorizationHandler,
                           ROLAC.API.Authorization.PermissionAuthorizationHandler>();

// Real-time hub for the live Sunday attendance counter.
builder.Services.AddSignalR();

// ---------------------------------------------------------------------------
// Swagger / MVC
// ---------------------------------------------------------------------------
builder.Services
    .AddControllers()
    .AddJsonOptions(opt =>
    {
        // camelCase in/out + tolerant DateOnly (accepts "yyyy-MM-dd" or full ISO datetime).
        opt.JsonSerializerOptions.PropertyNamingPolicy   = JsonNamingPolicy.CamelCase;
        opt.JsonSerializerOptions.DictionaryKeyPolicy    = JsonNamingPolicy.CamelCase;
        opt.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
        opt.JsonSerializerOptions.Converters.Add(new TolerantDateOnlyConverter());
    });
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddHealthChecks();
builder.Services.AddSwaggerGen(opt =>
{
    opt.SwaggerDoc("v1", new() { Title = "ROLAC API", Version = "v1" });

    // Enable JWT in Swagger UI
    opt.AddSecurityDefinition("Bearer", new()
    {
        Name         = "Authorization",
        Type         = Microsoft.OpenApi.Models.SecuritySchemeType.Http,
        Scheme       = "Bearer",
        BearerFormat = "JWT",
        In           = Microsoft.OpenApi.Models.ParameterLocation.Header,
        Description  = "Enter your JWT access token.",
    });
    opt.AddSecurityRequirement(new()
    {
        {
            new() { Reference = new() { Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme, Id = "Bearer" } },
            []
        }
    });
});

// ---------------------------------------------------------------------------
// Build
// ---------------------------------------------------------------------------
var app = builder.Build();

// Behind a TLS-terminating reverse proxy (nginx), honour the original scheme/client IP.
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});

// First in the pipeline: catch every unhandled exception, log it to SystemLogs, and return
// a clean problem+json. Placed after UseForwardedHeaders so the logged client IP is correct.
app.UseMiddleware<ExceptionHandlingMiddleware>();

// Apply migrations + seed on startup
using (var scope = app.Services.CreateScope())
{
    var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    await db.Database.MigrateAsync();
    await DbSeeder.SeedAsync(scope.ServiceProvider);
}

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// TLS is terminated by nginx in production; only redirect in local dev.
if (app.Environment.IsDevelopment())
{
    app.UseHttpsRedirection();
}

app.UseCors("Angular");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapHub<ROLAC.API.Hubs.AttendanceHub>("/hubs/attendance");
app.MapHub<ROLAC.API.Hubs.OfferingEntryHub>("/hubs/offering-entry");
app.MapHealthChecks("/health");

app.Run();
