require 'rails_helper'
require 'webmock/rspec'

RSpec.describe CreateLndhubAccountJob, type: :job do
  let(:user) { create :user, cn: "willherschel", ou: "kosmos.org" }

  subject(:job) { described_class.perform_later(user) }

  before do
    stub_request(:post, "http://localhost:3026/v2/users")
      .to_return(status: 200, headers: {},
                 body: { login: "abc123", password: "def456" }.to_json)
  end

  it "creates a new LndHub account" do
    perform_enqueued_jobs { job }

    expect(WebMock).to have_requested(:post, "http://localhost:3026/v2/users")
      .with { |req| req.body == '{}' }

    user.reload
    expect(user.ln_account).to eq("abc123")
    expect(user.ln_password).to eq("def456")
  end

  context "with existing credentials stored" do
    before do
      user.ln_account = "foo"
      user.ln_password = "bar"
      user.save!
    end

    it "does not create a new LndHub account" do
      perform_enqueued_jobs { job }

      expect(WebMock).to_not have_requested(:post, "http://localhost:3023/create")

      user.reload
      expect(user.ln_account).to eq("foo")
      expect(user.ln_password).to eq("bar")
    end
  end

  after do
    clear_enqueued_jobs
    clear_performed_jobs
  end
end
