# frozen_string_literal: true

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

class NonNanpOobPropertyTest < Minitest::Test
	def build_oob_message(dest, body, oob_url)
		m = Blather::Stanza::Message.new("#{dest}@component", body)
		m.from = "test@example.com/res"

		x = Nokogiri::XML::Node.new("x", m.document)
		ns = x.add_namespace(nil, "jabber:x:oob")
		url_node = Nokogiri::XML::Node.new("url", m.document)
		url_node.namespace = ns
		url_node.content = oob_url
		x.add_child(url_node)
		m.add_child(x)
		m
	end

	def test_non_nanp_oob_sends_url_as_text_not_mms
		property_of {
			dest = non_nanp_phone
			oob_path = sized(range(3, 12)) { string(:alnum) }
			oob_url = "https://example.com/media/#{oob_path}.jpg"
			[dest, message_body, oob_url]
		}.check { |dest, body, oob_url|
			reset_stanzas!
			reset_redis!

			bw_req = stub_request(:post, BW_MESSAGES_URL).with(
				body: hash_including(
					text: /#{Regexp.escape(oob_url)}/
				)
			).to_return(
				status: 201, body: JSON.dump(id: "bw-msg-non-nanp")
			)

			process_stanza(build_oob_message(dest, body, oob_url))

			assert_not_requested :head, oob_url
			assert_requested bw_req
		}
	end
	em :test_non_nanp_oob_sends_url_as_text_not_mms

	def test_nanp_oob_attempts_mms
		property_of {
			dest = nanpa_phone
			oob_path = sized(range(3, 12)) { string(:alnum) }
			oob_url = "https://example.com/media/#{oob_path}.jpg"
			[dest, message_body, oob_url]
		}.check { |dest, body, oob_url|
			reset_stanzas!
			reset_redis!

			bw_req = stub_request(:post, BW_MESSAGES_URL).with(
				body: hash_including(media: oob_url)
			).to_return(
				status: 201, body: JSON.dump(id: "bw-msg-nanp")
			)
			media_req = stub_request(:head, oob_url).to_return(
				status: 200,
				headers: {
					"Content-Length" => "500",
					"Content-Type" => "image/jpeg"
				}
			)

			process_stanza(build_oob_message(dest, body, oob_url))

			assert_requested :head, oob_url
			assert_requested bw_req
			assert_requested media_req
		}
	end
	em :test_nanp_oob_attempts_mms
end
