module Preview
  class HtmlMetadataExtractor
    IMAGE_SELECTORS = [
      'meta[property="og:image"]',
      'meta[name="twitter:image"]',
      'meta[name="thumbnail"]'
    ].freeze

    def self.extract(response)
      document = Nokogiri::HTML.parse(response.body)
      image_url = IMAGE_SELECTORS.filter_map {
        document.at_css(_1)&.[]('content')&.strip.presence
      }.first

      { title: document.at_css('title')&.text&.strip,
        image_url: image_url ? URI.join(response.url, image_url).to_s : nil }
    rescue URI::InvalidURIError
      { title: document.at_css('title')&.text&.strip, image_url: nil }
    end
  end
end
