using GeoRitmMover.GeoRitm.Data;
using GeoRitmMover.Mover.Data;
using GeoRitmMover.Services;
using GeoRitmMover.Services.Implementations;
using GeoRitmMover.Services.Implementations.TableMovers;

using Microsoft.EntityFrameworkCore;

using Monitoring.Common;

#if !DEBUG
using Monitoring.Common;
#endif
using Monitoring.Infrastructure.Data;
using Monitoring.Infrastructure.Services;

using Serilog;

var sourceConnectionString = EnvironmentVariables.Get("SOURCE_DATABASE_CONNECTION_STRING");
var middlewareConnectionString = EnvironmentVariables.Get("MIDDLEWARE_DATABASE_CONNECTION_STRING");
var destinationConnectionString = EnvironmentVariables.Get("DESTINATION_DATABASE_CONNECTION_STRING");

var host = Host.CreateDefaultBuilder(args)
	.ConfigureServices(services =>
	{
		_ = services.AddDbContext<GeoRitmDbContext>(options =>
		{
			_ = options.UseMySQL(sourceConnectionString)
				.EnableSensitiveDataLogging(false);
		});

		_ = services.AddDbContext<MoverDbContext>(options =>
		{
			_ = options.UseNpgsql(middlewareConnectionString)
				.EnableSensitiveDataLogging(false);
		});

		_ = services.AddDbContext<DataContext>(options =>
		{
			_ = options.UseNpgsql(destinationConnectionString)
				.EnableSensitiveDataLogging(false);
		});

		_ = services.AddHostedService<MovingBackgroundService>();
		_ = services.AddScoped<ITableMoverFactory, TableMoverFactory>();
		_ = services.AddScoped<IContexts, Contexts>();
		_ = services.AddScoped<TimeService>();
		_ = services.AddScoped<StringCutter>();

		_ = services.AddScoped<ClearAllTableMover>();
		_ = services.AddScoped<AssetGroupTableMover>();
		_ = services.AddScoped<AssetTableMover>();
		_ = services.AddScoped<AreaTableMover>();
		_ = services.AddScoped<ZoneTableMover>();
		_ = services.AddScoped<PhotoTableMover>();
		_ = services.AddScoped<EventTableMover>();
		_ = services.AddScoped<UserTableMover>();
		_ = services.AddScoped<EventCodeTableMover>();
		_ = services.AddScoped<AccessTableMover>();

		// dependencies
		_ = services.AddInfrastructureServices();

		Log.Logger = new LoggerConfiguration()
			.Enrich.FromLogContext()
			.MinimumLevel.Information()
			.WriteTo.Console()
			.CreateLogger();
		services.AddSerilog();
	})
	.Build();

await ApplyMigrations(host);

await host.RunAsync();

static async Task ApplyMigrations(IHost app)
{
	var context = app.Services.CreateScope().ServiceProvider.GetRequiredService<MoverDbContext>();
	await context.Database.MigrateAsync();
}
