using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// ===============================
// DATABASE CONFIGURATION
// ===============================

// Get database connection string (Docker override support)
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
if (string.IsNullOrEmpty(connectionString))
{
    // Fallback to environment variable for Docker
    connectionString = Environment.GetEnvironmentVariable("DATABASE_CONNECTION_STRING");
}

if (string.IsNullOrEmpty(connectionString))
{
    throw new InvalidOperationException("Database connection string not configured. Set ConnectionStrings:DefaultConnection in appsettings.json or DATABASE_CONNECTION_STRING environment variable.");
}

// TODO: Add Entity Framework when ready
// builder.Services.AddDbContext<GameDbContext>(options =>
//     options.UseNpgsql(connectionString));

// ===============================
// AUTHENTICATION (JWT)
// ===============================

var jwtSection = builder.Configuration.GetSection("JWT");
var jwtSecret = jwtSection["SecretKey"]
    ?? Environment.GetEnvironmentVariable("JWT_SECRET_KEY");

if (string.IsNullOrEmpty(jwtSecret) || jwtSecret.Contains("REPLACE"))
{
    if (builder.Environment.IsDevelopment())
    {
        Console.WriteLine("WARNING: Using development JWT secret. Set JWT_SECRET_KEY environment variable for production.");
    }
    else
    {
        throw new InvalidOperationException("JWT_SECRET_KEY environment variable must be set for production.");
    }
}

// Add JWT Authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.RequireHttpsMetadata = !builder.Environment.IsDevelopment();
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = jwtSection["Issuer"],
            ValidAudience = jwtSection["Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(jwtSecret ?? "dev_jwt_secret_key_at_least_32_chars_long_not_for_production_use_only")),
            ClockSkew = TimeSpan.Zero
        };
    });

// ===============================
// REDIS CONFIGURATION
// ===============================

var redisConnection = builder.Configuration.GetConnectionString("Redis")
    ?? Environment.GetEnvironmentVariable("REDIS_CONNECTION_STRING")
    ?? "localhost:6379";

// TODO: Add Redis when ready
// builder.Services.AddSingleton<IConnectionMultiplexer>(provider =>
//     ConnectionMultiplexer.Connect(redisConnection));

// ===============================
// API SERVICES
// ===============================

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
    {
        Title = "Shadowed Realms API",
        Version = "v1",
        Description = "Medieval Fantasy Strategy MMO Backend API"
    });

    // JWT Bearer Authentication in Swagger
    options.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below.",
        Name = "Authorization",
        In = Microsoft.OpenApi.Models.ParameterLocation.Header,
        Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });

    options.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
    {
        {
            new Microsoft.OpenApi.Models.OpenApiSecurityScheme
            {
                Reference = new Microsoft.OpenApi.Models.OpenApiReference
                {
                    Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
});

// CORS configuration with environment variable support
var allowedOrigins = builder.Configuration.GetSection("AllowedOrigins").Get<string[]>()
    ?? Environment.GetEnvironmentVariable("ALLOWED_ORIGINS")?.Split(',')
    ?? new[] { "http://localhost:3000" };

builder.Services.AddCors(options =>
{
    options.AddPolicy("ShadowedRealmsPolicy", policy =>
    {
        policy.WithOrigins(allowedOrigins)
              .AllowAnyMethod()
              .AllowAnyHeader()
              .AllowCredentials();
    });
});

// ===============================
// HEALTH CHECKS
// ===============================

builder.Services.AddHealthChecks();
// TODO: Add database health checks when EF is configured
// .AddNpgSql(connectionString)
// .AddRedis(redisConnection);

// ===============================
// BUILD APPLICATION
// ===============================

var app = builder.Build();

// ===============================
// MIDDLEWARE PIPELINE
// ===============================

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "Shadowed Realms API V1");
        options.RoutePrefix = "swagger";
    });
}

app.UseHttpsRedirection();
app.UseCors("ShadowedRealmsPolicy");

// Authentication and Authorization (proper order)
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

// Health check endpoint
app.MapHealthChecks("/health");

// ===============================
// STARTUP LOGGING
// ===============================

var logger = app.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Shadowed Realms API starting...");
logger.LogInformation("Environment: {Environment}", app.Environment.EnvironmentName);

// Docker-specific logging
var containerId = Environment.GetEnvironmentVariable("CONTAINER_ID");
var kingdomIds = Environment.GetEnvironmentVariable("KINGDOM_IDS");

if (!string.IsNullOrEmpty(containerId))
{
    logger.LogInformation("Container ID: {ContainerId}", containerId);
}
if (!string.IsNullOrEmpty(kingdomIds))
{
    logger.LogInformation("Managing Kingdoms: {KingdomIds}", kingdomIds);
}

logger.LogInformation("API ready at /swagger (development) and /health");

app.Run();