using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using Microsoft.EntityFrameworkCore.Update;

namespace e_suite.Database.SqlServer;

public class DatabaseNameReplacerSqlGenerator : SqlServerMigrationsSqlGenerator
{
    public DatabaseNameReplacerSqlGenerator(
        MigrationsSqlGeneratorDependencies dependencies,
        ICommandBatchPreparer commandBatchPreparer
    )
        : base(dependencies, commandBatchPreparer)
    {
    }

    protected override void Generate(
        MigrationOperation operation,
        IModel? model,
        MigrationCommandListBuilder builder)
    {
        if (operation is SqlOperation sqlOperation)
        {
            var dbName = this.Dependencies.CurrentContext.Context.Database.GetDbConnection().Database;
            sqlOperation.Sql = sqlOperation.Sql.Replace("[DatabaseNameToReplace]", dbName);
        }

        base.Generate(operation, model, builder);
    }
}