using System.Data;
using Microsoft.EntityFrameworkCore;

namespace Managing.Infrastructure.Databases.PostgreSql;

/// <summary>
/// Helper class for managing PostgreSQL database connections in Entity Framework repositories
/// </summary>
public static class PostgreSqlConnectionHelper
{
    /// <summary>
    /// Ensures the database connection is open before executing queries
    /// </summary>
    /// <param name="context">The DbContext to manage the connection for</param>
    public static async Task EnsureConnectionOpenAsync(DbContext context)
    {
        if (context.Database.GetDbConnection().State != ConnectionState.Open)
        {
            await context.Database.OpenConnectionAsync();
        }
    }

    /// <summary>
    /// Safely closes the database connection if it was opened by us
    /// </summary>
    /// <param name="context">The DbContext to manage the connection for</param>
    public static async Task SafeCloseConnectionAsync(DbContext context)
    {
        if (context.Database.GetDbConnection().State == ConnectionState.Open)
        {
            await context.Database.CloseConnectionAsync();
        }
    }
}
