using AAIntegration.SimmonsBank.API.Configs;
using AAIntegration.SimmonsBank.API.Handlers;
using AAIntegration.SimmonsBank.API.Helpers;
using AAIntegration.SimmonsBank.API.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;

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

        // Add services to the container.

        // Authentication
        builder.Services.AddAuthentication()
        .AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>(ApiKeyAuthenticationOptions.DefaultScheme, null);

        // Authorization
        builder.Services.AddAuthorization(options => {
            AuthorizationPolicyBuilder defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(
                ApiKeyAuthenticationOptions.DefaultScheme
            );

            defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
            options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build();
        });


        builder.Services.AddControllers();
        // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen();

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

        DatabaseConfig dbConfig = builder.Configuration.GetSection("Database").Get<DatabaseConfig>();

        builder.Services.AddDbContext<DataContext>(opt =>
            opt.UseNpgsql(dbConfig.GetConnectionString()));

        builder.Services.AddScoped<IUserService, UserService>();
        builder.Services.AddScoped<ICacheService, CacheService>();

        builder.Services.AddScoped<ApiKeyAuthenticationHandler>();

        var app = builder.Build();

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

        app.UseHttpsRedirection();

        app.UseAuthorization();

        app.MapControllers();

        app.Run();
    }
}
