// See https://aka.ms/new-console-template for more information

using System.Text.Json;
using System.Text.Json.Serialization;
using Catalogger.Backend;
using Catalogger.Backend.Database;
using Catalogger.Backend.Extensions;
using Microsoft.Extensions.Configuration;
using NodaTime;
using NodaTime.Serialization.SystemTextJson;
using NodaTime.Text;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.SystemConsole.Themes;

namespace Catalogger.GoImporter;

internal class Program
{
    public static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions
    {
        NumberHandling = JsonNumberHandling.AllowReadingFromString,
    }.ConfigureForNodaTime(
        new NodaJsonSettings
        {
            InstantConverter = new NodaPatternConverter<Instant>(InstantPattern.ExtendedIso),
        }
    );

    public static async Task Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .Enrich.FromLogContext()
            .MinimumLevel.Debug()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .WriteTo.Console(theme: AnsiConsoleTheme.Sixteen)
            .CreateLogger();

        var config = new ConfigurationBuilder().AddConfiguration().Build().Get<Config>();
        if (config == null)
        {
            Log.Fatal("No configuration object was created");
            return;
        }

        var db = new DatabasePool(config, Log.Logger, null);
        DatabasePool.ConfigureDapper();
        if (Environment.GetEnvironmentVariable("MIGRATE") == "true")
        {
            var migrator = new DatabaseMigrator(
                Log.Logger,
                SystemClock.Instance,
                await db.AcquireAsync()
            );

            await migrator.MigrateUp();
        }

        var type = args[0].ToLowerInvariant();
        var file = args[1];

        if (type == "guilds")
        {
            Log.Information("Importing guilds from {File}", file);
            await GuildImport.DoImportAsync(await db.AcquireAsync(), file);
        }
        else if (type == "messages")
        {
            Log.Information("Importing messages from {Path}", file);
            await MessageImport.DoImportAsync(config, await db.AcquireAsync(), file);
        }
    }
}
