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

using e_suite.API.Common.extensions;
using e_suite.Database.Migrator.Migrations;
using e_suite.Database.Migrator.SqlWrapper;
using e_suite.Database.SqlServer;
using eSuite.Core.Clock;
using Microsoft.EntityFrameworkCore;

Console.WriteLine($"Environment: {Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")}");

var configuration = ESuiteDatabaseExtension.BuildConfiguration();

var databaseName = configuration.GetConfigValue("SQL_DATABASE", "database:databaseName", "esuite")!;
var resetDatabaseName = configuration.GetConfigValue("RESET_DATABASE", "database:resetDatabase", false);

var connectionString = ESuiteDatabaseExtension.BuildConnectionString(configuration);

if (resetDatabaseName)
    PrePostScriptRunner.RunScripts(connectionString, databaseName, ScriptType.resetDatabase);

PrePostScriptRunner.RunScripts(connectionString, databaseName, ScriptType.preMigration);

Console.WriteLine("Migrating database");
try
{
    var database = await ESuiteDatabaseExtension.CreateDatabase(new UtcClock());
    database.Database.Migrate();

    Console.WriteLine("Database migration completed");
}
catch (Exception e)
{
    Console.WriteLine("Database migration failed");
    Console.WriteLine(e);
    throw;
}

PrePostScriptRunner.RunScripts(connectionString, databaseName, ScriptType.postMigration);