using InfluxDB.Client;
using Managing.Infrastructure.Databases.InfluxDb.Abstractions;

namespace Managing.Infrastructure.Databases.InfluxDb;

public class InfluxDbRepository : IInfluxDbRepository
{
    private readonly string _token;
    private readonly string _url;
    public string Organization { get; set; }

    public InfluxDbRepository(IInfluxDbSettings settings)
    {
        _token = settings.Token;
        _url = settings.Url;
        Organization = settings.Organization;
    }

    public void Write(Action<WriteApi> action)
    {
        using var client = InfluxDBClientFactory.Create(_url, _token);
        using var write = client.GetWriteApi();
        action(write);
    }

  public Task WriteAsync(Func<WriteApi, Task> action)
    {
        // Get write API asynchronously
        using var client = new InfluxDBClient(_url, _token);
        using var write = client.GetWriteApi();
        return action(write);
    }
    public async Task<T> QueryAsync<T>(Func<QueryApi, Task<T>> action)
    {
        using var client = InfluxDBClientFactory.Create(_url, _token);
        var query = client.GetQueryApi();
        return await action(query);
    }
}