using System.IO;
using Knot.Modules.Conversations.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.Configuration;

namespace Knot.Modules.Conversations.Infrastructure;

[DbContext(typeof(ChatsDbContext))]
public class ChatsDbContextFactory : IDesignTimeDbContextFactory<ChatsDbContext>
{
    public ChatsDbContext 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<ChatsDbContext>();
        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 ChatsDbContext(optionsBuilder.Options);
    }
}
