using ZB.MOM.WW.MxGateway.Server;
using ZB.MOM.WW.MxGateway.Server.Configuration;
using ZB.MOM.WW.MxGateway.Server.Security.Authentication;

ApiKeyAdminParseResult apiKeyAdminCommand = ApiKeyAdminCommandLineParser.Parse(args);
if (apiKeyAdminCommand.IsApiKeyCommand)
{
    if (apiKeyAdminCommand.Command is null)
    {
        await Console.Error.WriteLineAsync(apiKeyAdminCommand.Error);
        return 2;
    }

    WebApplicationBuilder builder = GatewayApplication.CreateBuilder([]);
    ApplyApiKeyAdminOverrides(builder.Configuration, apiKeyAdminCommand.Command);
    await using WebApplication cliApp = builder.Build();
    await using AsyncServiceScope scope = cliApp.Services.CreateAsyncScope();

    ApiKeyAdminCliRunner runner = scope.ServiceProvider.GetRequiredService<ApiKeyAdminCliRunner>();

    return await runner.RunAsync(apiKeyAdminCommand.Command, Console.Out, CancellationToken.None);
}

WebApplication app = GatewayApplication.Build(args);

app.Run();

return 0;

static void ApplyApiKeyAdminOverrides(IConfiguration configuration, ApiKeyAdminCommand command)
{
    if (!string.IsNullOrWhiteSpace(command.SqlitePath))
    {
        configuration[$"{GatewayOptions.SectionName}:Authentication:SqlitePath"] = command.SqlitePath;
    }

    if (!string.IsNullOrWhiteSpace(command.Pepper))
    {
        configuration["MxGateway:ApiKeyPepper"] = command.Pepper;
    }
}

public partial class Program;
