using Npgsql;

namespace PlanTempus.X.TDD.CodeSnippets;

internal class TestPostgresLISTENNOTIFY
{
    private static async Task Main(string[] args)
    {
        var connectionString = "Host=192.168.1.63;Database=ptdb01;Username=postgres;Password=3911";

        try
        {
            await using var conn = new NpgsqlConnection(connectionString);
            await conn.OpenAsync();

            Console.WriteLine("Forbundet til databasen. Lytter efter notifikationer...");

            conn.Notification += (o, e) =>
            {
                Console.WriteLine("Notifikation modtaget:");
                Console.WriteLine($"  PID: {e.PID}");
                Console.WriteLine($"  Kanal: {e.Channel}");
                Console.WriteLine($"  Payload: {e.Payload}");
                Console.WriteLine("------------------------");
            };

            await using (var cmd = new NpgsqlCommand("LISTEN config_changes;", conn))
            {
                await cmd.ExecuteNonQueryAsync();
            }

            Console.WriteLine("Tryk på en tast for at stoppe...");

            while (!Console.KeyAvailable) await conn.WaitAsync();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Der opstod en fejl: {ex.Message}");
            Console.WriteLine($"Stack trace: {ex.StackTrace}");
        }
    }
}