using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Persistence;

/// <summary>
/// Design-time DbContext factory for EF Core migrations
/// </summary>
public class PMDbContextFactory : IDesignTimeDbContextFactory<PMDbContext>
{
    public PMDbContext CreateDbContext(string[] args)
    {
        // Get connection string from environment or use default matching appsettings.Development.json
        var connectionString = Environment.GetEnvironmentVariable("PMDatabase")
            ?? "Host=localhost;Port=5432;Database=colaflow_pm;Username=colaflow;Password=colaflow_dev_password";

        // Create DbContext options
        var optionsBuilder = new DbContextOptionsBuilder<PMDbContext>();
        optionsBuilder.UseNpgsql(connectionString, b => b.MigrationsAssembly("ColaFlow.Modules.ProjectManagement.Infrastructure"));

        // Create DbContext with a mock HttpContextAccessor (for migrations only)
        return new PMDbContext(optionsBuilder.Options, new MockHttpContextAccessor());
    }

    /// <summary>
    /// Mock HttpContextAccessor for design-time operations
    /// Returns null HttpContext which PMDbContext handles gracefully
    /// </summary>
    private class MockHttpContextAccessor : IHttpContextAccessor
    {
        public HttpContext? HttpContext { get; set; } = null;
    }
}
