using System.Reflection;
using DbUp;
using Microsoft.Extensions.Logging;

namespace SatelliteProvider.DataAccess;

public class DatabaseMigrator
{
    private readonly string _connectionString;
    private readonly ILogger<DatabaseMigrator>? _logger;

    public DatabaseMigrator(string connectionString, ILogger<DatabaseMigrator>? logger = null)
    {
        _connectionString = connectionString;
        _logger = logger;
    }

    public bool RunMigrations()
    {
        _logger?.LogInformation("Starting database migrations...");

        EnsureDatabase.For.PostgresqlDatabase(_connectionString);

        var upgrader = DeployChanges.To
            .PostgresqlDatabase(_connectionString)
            .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly(),
                script => script.Contains(".Migrations."))
            .LogToConsole()
            .Build();

        var result = upgrader.PerformUpgrade();

        if (!result.Successful)
        {
            _logger?.LogError(result.Error, "Database migration failed");
            return false;
        }

        _logger?.LogInformation("Database migrations completed successfully");
        return true;
    }
}

