# typed: strict
# frozen_string_literal: true

class YettoService
  cattr_reader :yetto_client, instance_accessor: false do
    Httpsensible::Client.new(user_agent: "PlugApp/#{PlugApp::Application::GIT_SHA}")
  end

  # explicitly different than what's in environment.rb, because local
  # Yetto expects HTTP; environment.rb can use HTTPS because it passes through ngrok.io
  PROTOCOL = Rails.env.development? ? "http://" : "https://"
  YETTO_API_VERSION_TLD = "#{PROTOCOL}://#{YETTO_API_TLD}/#{YETTO_API_VERSION}"
  JWT_ALGORITHM = "RS256"

  class << self
    def perform_token_exchange(plug_installation_id)
      encoded_jwt = Httpsensible::JWT.encode_jwt(YETTO_PLUG_PEM, YETTO_PLUG_ID)
      response = yetto_client.with_headers({ "Authorization" => "Bearer #{encoded_jwt}" }).post("#{YETTO_API_VERSION_TLD}/plug/installations/#{plug_installation_id}/access_tokens")
      body = response.parsed_json_body
      body["token"]
    end

    def get_plug_installation(plug_installation_id)
      token = perform_token_exchange(plug_installation_id)
      yetto_client.with_headers("Authorization" => "Bearer #{token}").get("#{YETTO_API_VERSION_TLD}/installations/#{plug_installation_id}")
    end

    def update_installation(plug_installation_id, params)
      plug_installation = {}
      plug_installation[:settings] = params.fetch(:settings, {})
      plug_installation[:credentials] = params.fetch(:credentials, {})

      token = perform_token_exchange(plug_installation_id)
      yetto_client.with_headers("Authorization" => "Bearer #{token}").patch("#{YETTO_API_VERSION_TLD}/installations/#{plug_installation_id}", json: plug_installation)
    end

    def create_inbox_switch(inbox_id, plug_installation_id, params)
      payload = params[:payload]
      token = perform_token_exchange(plug_installation_id)

      yetto_client.with_headers("Authorization" => "Bearer #{token}").post("#{YETTO_API_VERSION_TLD}/inboxes/#{inbox_id}/switches", json: payload)
    end

    def update_message(message_id, plug_installation_id, params)
      payload = params[:payload]
      token = perform_token_exchange(plug_installation_id)

      yetto_client.with_headers("Authorization" => "Bearer #{token}").patch("#{YETTO_API_VERSION_TLD}/messages/#{message_id}", json: payload)
    end

    def create_message_reply(message_id, plug_installation_id, params)
      payload = params[:payload]
      token = perform_token_exchange(plug_installation_id)

      yetto_client.with_headers("Authorization" => "Bearer #{token}").post("#{YETTO_API_VERSION_TLD}/messages/#{message_id}/replies", json: payload)
    end
  end
end