using System.CommandLine;
using Electricity.Api;
using Electricity.Api.Services;
using Microsoft.EntityFrameworkCore;

var rootCommand = new RootCommand("ElectricityServer is a small REST API to access the electricity log database");
var connectionStringArgument = new Option<string>(
    name: "--connection-string",
    description: "Filepath to the Sqlite3 database file (*.db)");
rootCommand.AddOption(connectionStringArgument);

var result = rootCommand.Parse(args);

if (result.Errors.Any())
{
    foreach (var error in result.Errors)
    {
        Console.WriteLine(error.Message);
    }
    return 1;
}

var sqlite3DatabaseFilePath = result.GetValueForOption(connectionStringArgument);
if (!File.Exists(sqlite3DatabaseFilePath))
{
    Console.WriteLine($"Sqlite3 database <{sqlite3DatabaseFilePath}> does not exist or is inaccessible");
    return 1;
}

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<DatabaseContext>((DbContextOptionsBuilder builder) =>
{
    builder.UseSqlite($"Data Source={sqlite3DatabaseFilePath}");
});

builder.Services.AddControllers()
    .AddJsonOptions(config =>
    {
        config.JsonSerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
        config.JsonSerializerOptions.WriteIndented = true;
    });
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<ElectricityService>();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseHttpsRedirection();
    app.UseSwagger();
    app.UseSwaggerUI();
    app.UseCors("default");
}

app.UseMiddleware<Electricity.Api.Middlewares.IpFilterMiddleware>();
app.UseAuthorization();

app.MapControllers();

app.Run();

return 0;