# frozen_string_literal: true

class OutgoingMMS
	def self.for(m)
		body = m.body.sub(m.oobs.first&.url.to_s, "")
		OutgoingMMS.new(
			addresses: m.addresses ||
				[Addresses::Address.new(uri: "sms:#{m.to.node}")],
			body: body,
			urls: m.oobs&.map(&:url)
		)
	end

	def initialize(addresses:, body: nil, urls: nil)
		@addresses = addresses.to_a
		@to = @addresses.pop
		@body = body
		@urls = urls
	end

	def as_json(*)
		{
			encoding: :native,
			recip: @addresses.map { |adr| adr.uri.sub(/\Asms:\+?/, "") }.join(",")
		}
			.merge(@urls ? { files: @urls.join(",") } : {})
			.merge(@body && !@body.empty? ? { textmessagebody: @body } : {})
	end

	def to_json(*)
		as_json.to_json
	end

	def to_stanza(id:, from:)
		Blather::Stanza::Message.new(@to.jid, to_json).tap do |m|
			m.id = id
			m.from =
				ProxiedJID.proxy(from, CONFIG[:component][:jid])
					.with(resource: "#{from.resource}/#{m.id}")
		end
	end
end
