using System.Data;
using Npgsql;

namespace ComputerSalesApp.Data;

internal static class Db
{
    public static NpgsqlConnection CreateConnection()
    {
        return new NpgsqlConnection(ConnectionSettings.ConnectionString);
    }

    public static async Task<DataTable> QueryAsync(string sql, Action<NpgsqlParameterCollection>? configureParameters = null)
    {
        await using var connection = CreateConnection();
        await connection.OpenAsync();

        await using var command = new NpgsqlCommand(sql, connection);
        configureParameters?.Invoke(command.Parameters);

        await using var reader = await command.ExecuteReaderAsync();
        var table = new DataTable();
        table.Load(reader);
        return table;
    }

    public static async Task<int> ExecuteAsync(string sql, Action<NpgsqlParameterCollection>? configureParameters = null)
    {
        await using var connection = CreateConnection();
        await connection.OpenAsync();

        await using var command = new NpgsqlCommand(sql, connection);
        configureParameters?.Invoke(command.Parameters);

        return await command.ExecuteNonQueryAsync();
    }
}
