using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Quartz;
using FutureMailAPI.Data;
using FutureMailAPI.Helpers;
using FutureMailAPI.Services;
using FutureMailAPI.Filters;
using Microsoft.Extensions.FileProviders;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// 配置服务器监听所有网络接口的5003端口
builder.WebHost.ConfigureKestrel(options =>
{
    options.ListenAnyIP(5003);
});

// 配置数据库连接
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<FutureMailDbContext>(options =>
    options.UseSqlite(connectionString));

// 配置Swagger/OpenAPI
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "FutureMail API", Version = "v1" });
    c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
    
    // 添加文件上传支持
    c.OperationFilter<FileUploadOperationFilter>();
});

// 注册服务
builder.Services.AddScoped<IPasswordHelper, PasswordHelper>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IMailService, MailService>();
builder.Services.AddScoped<ITimeCapsuleService, TimeCapsuleService>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IOAuthService, OAuthService>();
builder.Services.AddScoped<IAIAssistantService, AIAssistantService>();
builder.Services.AddScoped<IPersonalSpaceService, PersonalSpaceService>();
builder.Services.AddScoped<IFileUploadService, FileUploadService>();
builder.Services.AddScoped<INotificationService, NotificationService>();

builder.Services.AddScoped<IInitializationService, InitializationService>();

// 添加JWT认证
var jwtSettings = builder.Configuration.GetSection("Jwt");
var key = Encoding.ASCII.GetBytes(jwtSettings["Key"] ?? throw new InvalidOperationException("JWT密钥未配置"));

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.RequireHttpsMetadata = false;
    options.SaveToken = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ValidateIssuer = true,
        ValidIssuer = jwtSettings["Issuer"],
        ValidateAudience = true,
        ValidAudience = jwtSettings["Audience"],
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero
    };
});

builder.Services.AddAuthorization();

// 配置Quartz任务调度
builder.Services.AddQuartz(q =>
{
    // 注册邮件投递任务
    var jobKey = new JobKey("MailDeliveryJob");
    q.AddJob<MailDeliveryJob>(opts => opts.WithIdentity(jobKey));
    
    // 创建触发器 - 每分钟执行一次
    q.AddTrigger(opts => opts
        .ForJob(jobKey)
        .WithIdentity("MailDeliveryJob-trigger")
        .WithCronSchedule("0 * * ? * *")); // 每分钟执行一次
});

// 添加Quartz主机服务
builder.Services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);

// 添加控制器并注册OAuth认证过滤器为全局过滤器
builder.Services.AddControllers(options =>
{
    options.Filters.Add<OAuthAuthenticationFilter>();
});

// 添加CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    });
});

var app = builder.Build();

// 初始化系统数据
using (var scope = app.Services.CreateScope())
{
    var initializationService = scope.ServiceProvider.GetRequiredService<IInitializationService>();
    await initializationService.InitializeAsync();
}

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

// 配置静态文件服务
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "uploads")),
    RequestPath = "/uploads"
});

app.UseCors("AllowAll");



app.MapControllers();

app.Run();
