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.
/// </summary>
/// <remarks>
///     Set the variable before running migration commands, e.g.:
///     <code>
///         $env:OTOPCUA_CONFIG_CONNECTION = "Server=10.100.0.35,14330;Database=OtOpcUaConfig;Trusted_Connection=True;TrustServerCertificate=True;"
///         dotnet ef migrations add MyMigration --project src/Core/ZB.MOM.WW.OtOpcUa.Configuration
///     </code>
///     No credential is embedded in source. Do not add a plaintext password as a fallback.
/// </remarks>
public sealed class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<OtOpcUaConfigDbContext>
{
    /// <summary>Creates a new DbContext instance for design-time operations.</summary>
    /// <param name="args">Command-line arguments (unused).</param>
    /// <returns>The configured DbContext instance.</returns>
    public OtOpcUaConfigDbContext CreateDbContext(string[] args)
    {
        var connection = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_CONNECTION");

        if (string.IsNullOrWhiteSpace(connection))
            throw new InvalidOperationException(
                "OTOPCUA_CONFIG_CONNECTION is not set. " +
                "Export the variable before running 'dotnet ef' commands. Example: " +
                "Server=10.100.0.35,14330;Database=OtOpcUaConfig;Trusted_Connection=True;TrustServerCertificate=True;");

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

        return new OtOpcUaConfigDbContext(options);
    }
}
