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

namespace Knot.Shared.Infrastructure.Persistence;

public class SystemDbContextFactory : IDesignTimeDbContextFactory<SystemDbContext>
{
    public SystemDbContext CreateDbContext(string[] args)
    {
        var basePath = Path.Combine(Directory.GetCurrentDirectory(), "..", "Host");
        if (!Directory.Exists(basePath))
        {
            basePath = Directory.GetCurrentDirectory(); // fallback
        }

        var configuration = new ConfigurationBuilder()
            .SetBasePath(basePath)
            .AddJsonFile("appsettings.json", optional: true)
            .AddEnvironmentVariables()
            .Build();

        var builder = new DbContextOptionsBuilder<SystemDbContext>();
        var connectionString = configuration.GetConnectionString("DefaultConnection")
            ?? configuration["DATABASE_URL"]
            ?? "Host=localhost;Port=5432;Database=knot_db;Username=knot;Password=knot_pass";

        builder.UseNpgsql(connectionString);

        return new SystemDbContext(builder.Options);
    }
}
