class SycamoreBlogSsoService < ApplicationService
  def call
    url = "#{base_url}/sso/v1/auth&#{authentication_params}"
    response = JSON.parse(RestClient.post(url, {}))

    "#{base_url}/sso/v1/autologin&JWT=#{response['data']['jwt']}"
  end

  def recent_posts(indiana_only)
    response = JSON.parse(RestClient.get("#{base_url}/wp/v2/posts"))

    [].tap do |posts|
      response.each do |data|
        next unless data['status'] == 'publish'
        # Tags with ID 108 are Indiana-specific posts
        next if indiana_only && data['tags'].exclude?(108)
        next if data['tags'].include?(108) && !indiana_only

        posts << { date: data['date'], title: data['title']['rendered'], link: data['link'] }
        return posts if posts.count == 3
      end
    end
  end

  private
    def base_url
      'https://sycamoresupport.com/knowledge/?rest_route='
    end

    def authentication_params
      {
        email: ENV['SYCAMORE_BLOG_EMAIL'],
        password: ENV['SYCAMORE_BLOG_PASSWORD'],
        auth_key: ENV['SYCAMORE_BLOG_AUTH_KEY']
      }.to_query
    end
end
