# frozen_string_literal: true

require "test_helper"
require_relative "../../sgx-bwmsgsv2"
require "rantly/minitest_extensions"
require_relative "rantly_extensions/data_extensions"

class ToCatapultPropertyTest < Minitest::Test
	def test_accepts_201_and_202_with_escaped_tag
		property_of {
			dest = nanpa_phone
			guard(dest != "+15550000000")

			stanza_id = maybe_http_escapable_string
			resource = maybe_http_escapable_string
			status = choose(201, 202)

			[dest, message_body(nil_pct: 0, empty_pct: 0), stanza_id, resource, status]
		}.check { |dest, body, stanza_id, resource, status|
			reset_stanzas!
			reset_redis!
			WebMock.reset!

			bw_request_body = nil
			bw_req = stub_request(:post, BW_MESSAGES_URL).to_return { |request|
				bw_request_body = JSON.parse(request.body)
				{
					status: status,
					body: JSON.dump(id: "bw-msg-id", time: Time.now.iso8601)
				}
			}

			m = Blather::Stanza::Message.new("#{dest}@component", body)
			m.from = "test@example.com/#{resource}"
			m.id = stanza_id

			process_stanza(m)

			expected_tag = WEBrick::HTTPUtils.escape(stanza_id) +
				" " +
				WEBrick::HTTPUtils.escape(resource)
			assert_equal expected_tag, bw_request_body["tag"],
				"Tag should be HTTP-escaped (status=#{status})"

			assert_requested bw_req

			written.each do |response|
				stanza = Blather::XMPPNode.parse(response.to_xml)
				refute stanza.error?,
					"Expected success for status #{status} but got error"
			end
		}
	end
	em :test_accepts_201_and_202_with_escaped_tag
end
