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

namespace ColaFlow.Modules.Mcp.Infrastructure.Persistence;

/// <summary>
/// Design-time factory for McpDbContext (used by EF Core migrations)
/// </summary>
public class McpDbContextFactory : IDesignTimeDbContextFactory<McpDbContext>
{
    public McpDbContext CreateDbContext(string[] args)
    {
        // Build configuration
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false)
            .AddJsonFile("appsettings.Development.json", optional: true)
            .AddEnvironmentVariables()
            .Build();

        // Get connection string
        var connectionString = configuration.GetConnectionString("DefaultConnection");
        if (string.IsNullOrEmpty(connectionString))
        {
            throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
        }

        // Build DbContextOptions
        var optionsBuilder = new DbContextOptionsBuilder<McpDbContext>();
        optionsBuilder.UseNpgsql(connectionString);

        return new McpDbContext(optionsBuilder.Options);
    }
}
