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

namespace Knot.Modules.Relations.Infrastructure.Persistence;

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

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

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

        optionsBuilder.UseNpgsql(connectionString);

        return new RelationsDbContext(optionsBuilder.Options, null!);
    }
}
