using System.Reflection;
using CvCleanupJob.Tasks;
using JobScheduler.Scheduling;
using JobScheduler.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Models.Settings;
using Serilog;
using StartupHelpers;

const string ServiceName = "cv-cleanup-job";

StartupExtensions.LoadDotEnvFile();
var appVersion = StartupExtensions.GetApplicationVersion(Assembly.GetExecutingAssembly());

try
{
    var builder = Host.CreateApplicationBuilder(args);

    builder.ConfigureJsonSerilog(ServiceName, appVersion);
    Log.Information("Starting {Service} version {AppVersion}", ServiceName, appVersion);

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

    builder.Services.AddSingleton<CvStorageCleanupJobTask>();
    builder.Services.AddSingleton<IEnumerable<IJobTask>>(sp => new IJobTask[]
    {
        sp.GetRequiredService<CvStorageCleanupJobTask>(),
    });

    builder.Services.AddHostedService<JobSchedulerHostedService>();

    var host = builder.Build();

    host.LogHostStartupDiagnostics(ServiceName);

    Log.Information("{Service} startup complete. Background scheduler is running.", ServiceName);
    await host.RunAsync();
}
catch (Exception ex)
{
    Log.Fatal(ex, "{Service} terminated unexpectedly", ServiceName);
}
finally
{
    Log.CloseAndFlush();
}
