require 'rails_helper'
require 'webmock/rspec'

RSpec.describe "/api/btcpay", type: :request do

  describe "GET /onchain_btc_balance" do
    before do
      stub_request(:get, "http://btcpay.example.com/api/v1/stores/123456/payment-methods/onchain/BTC/wallet")
        .to_return(status: 200, headers: {}, body: {
          balance: 0.91108606,
          unconfirmedBalance: 0,
          confirmedBalance: 0.91108606
        }.to_json)
    end

    it "returns a formatted result for the onchain wallet balance" do
      get api_btcpay_onchain_btc_balance_path

      expect(response).to have_http_status(:ok)

      res = JSON.parse(response.body)
      expect(res["balance"]).to eq(91108606)
      expect(res["unconfirmed_balance"]).to eq(0)
      expect(res["confirmed_balance"]).to eq(91108606)
    end

    context "upstream request error" do
      before do
        stub_request(:get, "http://btcpay.example.com/api/v1/stores/123456/payment-methods/onchain/BTC/wallet")
          .to_return(status: 500, headers: {}, body: "")
      end

      it "returns a formatted error" do
        get api_btcpay_onchain_btc_balance_path

        expect(response).to have_http_status(:server_error)

        res = JSON.parse(response.body)
        expect(res["error"]).not_to be_nil
      end
    end

    context "feature disabled" do
      before do
        Setting.btcpay_publish_wallet_balances = false
      end

      it "returns a 404 status" do
        get api_btcpay_onchain_btc_balance_path

        expect(response).to have_http_status(:not_found)
      end
    end
  end

  describe "GET /lightning_btc_balance" do
    before do
      stub_request(:get, "http://btcpay.example.com/api/v1/stores/123456/lightning/BTC/balance")
        .to_return(status: 200, headers: {}, body: {
          offchain: {
            local: 4200000000
          },
        }.to_json)
    end

    it "returns a formatted result for the onchain wallet balance" do
      get api_btcpay_lightning_btc_balance_path

      expect(response).to have_http_status(:ok)

      res = JSON.parse(response.body)
      expect(res["confirmed_balance"]).to eq(4200000)
    end

    context "upstream request error" do
      before do
        stub_request(:get, "http://btcpay.example.com/api/v1/stores/123456/lightning/BTC/balance")
          .to_return(status: 500, headers: {}, body: "")
      end

      it "returns a formatted error" do
        get api_btcpay_lightning_btc_balance_path

        expect(response).to have_http_status(:server_error)

        res = JSON.parse(response.body)
        expect(res["error"]).not_to be_nil
      end
    end

    context "feature disabled" do
      before do
        Setting.btcpay_publish_wallet_balances = false
      end

      it "returns a 404 status" do
        get api_btcpay_lightning_btc_balance_path

        expect(response).to have_http_status(:not_found)
      end
    end
  end
end
