using DbUp;
using Microsoft.Extensions.Logging;

namespace QuantEngine.Infrastructure.Data
{
    /// <summary>
    /// Database migration manager using DbUp.
    /// SQL migration files are embedded in the assembly under Migrations/ folder.
    /// Naming convention: V{version}__{description}.sql
    /// </summary>
    public class DbMigrator
    {
        private readonly string _connectionString;
        private readonly ILogger<DbMigrator> _logger;

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

        public void Migrate()
        {
            _logger.LogInformation("🔄 Starting database migration with DbUp...");

            try
            {
                var upgrader = DeployChanges.To
                    .PostgresqlDatabase(_connectionString)
                    .WithScriptsEmbeddedInAssembly(typeof(DbMigrator).Assembly, s => s.StartsWith("QuantEngine.Infrastructure.Migrations"))
                    .LogToConsole()
                    .Build();

                var result = upgrader.PerformUpgrade();

                if (!result.Successful)
                {
                    _logger.LogError("❌ Database migration failed: {Error}", result.Error?.Message);
                    throw new InvalidOperationException($"Database migration failed: {result.Error?.Message}");
                }

                _logger.LogInformation("✅ Database migration completed successfully");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "❌ Database migration failed");
                throw;
            }
        }
    }
}
