using System.Net.Http.Headers;
using Newtonsoft.Json;

namespace PayForReactions;

public class AlbyApi
{
    private readonly HttpClient _client;

    public AlbyApi(HttpClient client, Config config)
    {
        _client = client;
        _client.Timeout = TimeSpan.FromSeconds(60);
        _client.BaseAddress = new("https://api.getalby.com");
        _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(config.Alby.Type, config.Alby.Token);
    }

    public async Task<long> GetBalance()
    {
        var json = await _client.GetStringAsync("/balance");
        var obj = JsonConvert.DeserializeObject<BalanceResponse>(json);
        return (long?)obj?.Balance ?? 0L;
    }

    public async Task<bool> PayInvoice(string pr)
    {
        var rsp = await _client.PostAsync("/payments/bolt11", new StringContent(JsonConvert.SerializeObject(new
        {
            invoice = pr
        }), new MediaTypeHeaderValue("application/json")));

        return rsp.IsSuccessStatusCode;
    }

    class BalanceResponse
    {
        [JsonProperty("balance")]
        public decimal Balance { get; init; }

        [JsonProperty("currency")]
        public string Currency { get; init; } = "BTC";

        [JsonProperty("unit")]
        public string Unit { get; init; } = "sat";
    }
}
