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

namespace Backend.Data;

public sealed class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AwardsDbContext>
{
    public AwardsDbContext CreateDbContext(string[] args)
    {
        var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false)
            .AddJsonFile($"appsettings.{environment}.json", optional: true)
            .AddEnvironmentVariables()
            .Build();

        var optionsBuilder = new DbContextOptionsBuilder<AwardsDbContext>();
        var connectionString = configuration["VTSA_POSTGRES"]
            ?? configuration.GetConnectionString("Postgres");

        if (string.IsNullOrWhiteSpace(connectionString))
        {
            throw new InvalidOperationException(
                "No PostgreSQL connection string configured for design-time EF operations. " +
                "Set VTSA_POSTGRES or ConnectionStrings__Postgres before running dotnet ef.");
        }

        optionsBuilder.UseNpgsql(connectionString);
        return new AwardsDbContext(optionsBuilder.Options);
    }
}
