using DbUp;

var connectionString = Environment.GetEnvironmentVariable("KARTSELL_POSTGRES")
    ?? "Host=localhost;Port=5432;Database=kartsell;Username=kartsell;Password=kartsell";

var scriptsPath = Path.Combine(AppContext.BaseDirectory, "db", "migrations");
if (!Directory.Exists(scriptsPath))
{
    scriptsPath = Path.Combine(AppContext.BaseDirectory, "migrations");
}
if (!Directory.Exists(scriptsPath))
{
    // Fallback: SQL files are copied to bin root in flattened structure
    scriptsPath = AppContext.BaseDirectory;
}

EnsureDatabase.For.PostgresqlDatabase(connectionString);

var result = DeployChanges.To
    .PostgresqlDatabase(connectionString)
    .WithScriptsFromFileSystem(scriptsPath)
    .WithVariables(new Dictionary<string, string>())
    .JournalToPostgresqlTable("public", "kartsell_schema_versions")
    .LogToConsole()
    .Build()
    .PerformUpgrade();

if (!result.Successful)
{
    Console.Error.WriteLine(result.Error);
    return 1;
}

Console.WriteLine("Database migration completed.");
return 0;
