using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace ZB.MOM.WW.OtOpcUa.Configuration;

/// <summary>
///     Used by <c>dotnet ef</c> at design time (migrations, scaffolding). Reads the connection string
///     from the <c>OTOPCUA_CONFIG_CONNECTION</c> environment variable, falling back to the local dev
///     container on <c>localhost:1433</c>.
/// </summary>
public sealed class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<OtOpcUaConfigDbContext>
{
    // Host-port 14330 avoids collision with the native MSSQL14 instance on 1433 (Galaxy "ZB" DB).
    private const string DefaultConnectionString =
        "Server=localhost,14330;Database=OtOpcUaConfig;User Id=sa;Password=OtOpcUaDev_2026!;TrustServerCertificate=True;Encrypt=False;";

    public OtOpcUaConfigDbContext CreateDbContext(string[] args)
    {
        var connection = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_CONNECTION")
                         ?? DefaultConnectionString;

        var options = new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
            .UseSqlServer(connection, sql => sql.MigrationsAssembly(typeof(OtOpcUaConfigDbContext).Assembly.FullName))
            .Options;

        return new OtOpcUaConfigDbContext(options);
    }
}
