# frozen_string_literal: true

require "snikket"

class TestSnikket < Minitest::Test
	NS = "xmpp:snikket.org/hosting/v1"

	def test_launch
		launch = Snikket::Launch.new(domain: "example.com")
		assert_equal :set, launch.type
		assert_equal NS, launch.query.namespace.href
		assert_equal "launch", launch.query.node_name
		assert_equal(
			"example.com",
			launch.query.at_xpath("./ns:domain", ns: NS).content
		)
		assert_nil launch.query.at_xpath("./ns:test-instance", ns: NS)
	end

	def test_launch_test_instance
		launch = Snikket::Launch.new(
			domain: "jmp-test-example.com", test_instance: true
		)
		refute_nil launch.query.at_xpath("./ns:test-instance", ns: NS)
	end

	def test_launched
		launched = Blather::XMPPNode.parse(<<~XML)
			<iq type="result" from="hosting-api.snikket.net" id="123">
				<launched xmlns="xmpp:snikket.org/hosting/v1">
					<bootstrap>
						<token>fZLy6iTh</token>
					</bootstrap>
					<instance-id>si-12345</instance-id>
				</launched>
			</iq>
		XML
		assert_equal :result, launched.type
		assert_equal NS, launched.query.namespace.href
		assert_equal "launched", launched.query.node_name
		assert_equal "si-12345", launched.instance_id
	end

	def test_instance_get
		instance = Snikket::Instance.new(instance_id: "si-1234")
		assert_equal :get, instance.type
		assert_equal NS, instance.query.namespace.href
		assert_equal "instance", instance.query.node_name
		assert_equal(
			"si-1234",
			instance.query.at_xpath("./ns:instance-id", ns: NS).content
		)
	end

	def test_instance_result
		instance = Blather::XMPPNode.parse(<<~XML)
			<iq type="result" from="hosting-api.snikket.net" id="000">
				<instance xmlns="xmpp:snikket.org/hosting/v1">
					<update-needed/>
					<instance-id>si-1234</instance-id>
					<operation>
						<progress>50</progress>
						<status>running</status>
					</operation>
					<status>up</status>
				</instance>
			</iq>
		XML
		assert_equal :result, instance.type
		assert_equal NS, instance.query.namespace.href
		assert_equal "instance", instance.query.node_name
		assert_equal "si-1234", instance.instance_id
		assert instance.update_needed?
		assert_kind_of Nokogiri::XML::Element, instance.operation
		assert_equal :up, instance.status
	end

	def test_bootstrap_uri
		instance = Snikket::CustomerInstance.new(
			instance_id: "si-1234",
			bootstrap_token: "fZLy6iTh",
			customer_id: "test",
			domain: "example.com"
		)

		assert_equal(
			"https://example.com/invites_bootstrap?token=fZLy6iTh",
			instance.bootstrap_uri
		)
	end
end
