using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace ScadaLink.ConfigurationDatabase;

/// <summary>
/// Factory for creating DbContext instances at design time (used by dotnet ef tooling).
/// Reads connection string from Host's appsettings.Central.json.
/// </summary>
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<ScadaLinkDbContext>
{
    public ScadaLinkDbContext CreateDbContext(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "..", "ScadaLink.Host"))
            .AddJsonFile("appsettings.json", optional: true)
            .AddJsonFile("appsettings.Central.json", optional: true)
            .Build();

        var connectionString = configuration["ScadaLink:Database:ConfigurationDb"]
            ?? "Server=localhost,1433;Database=ScadaLink_Config;User Id=sa;Password=YourPassword;TrustServerCertificate=True";

        var optionsBuilder = new DbContextOptionsBuilder<ScadaLinkDbContext>();
        optionsBuilder.UseSqlServer(connectionString);

        return new ScadaLinkDbContext(optionsBuilder.Options);
    }
}
