module Games
  class AddCategoryTag < Games::Base
    GRAFFITI_ENDPOINT = Settings.graffiti.endpoint
    SERVICE_NAMESPACE = "/twirp/code.justin.tv.discovery.graffiti.rpc.graffiti.Graffiti"
    HEADERS = { 'Content-Type' => 'application/json' }

    attributes :game_id, :game_name, :tag_id, :tag_name, :ldap_login
    validates :game_id, :tag_id, :ldap_login, presence: true

    def save
      if self.game_id.blank? || self.tag_id.blank?
        self.errors.add(:base, "Please click on autocomplete results instead of manually enter the full names so it fetches game_id and tag_id from Algolia.")
        return false
      end
      payload = {}

      payload["content_id"] = self.game_id
      payload["tag_ids"] = []
      payload["tag_ids"].push(self.tag_id)
      payload["content_type"] = "CATEGORY"
      payload["modifier_id"] = self.ldap_login

      response = post(
        "#{GRAFFITI_ENDPOINT}#{SERVICE_NAMESPACE}/CreateContentTags",
        headers: HEADERS,
        body: payload.to_json
      )

      self.errors.add(:base, response.body["msg"]) unless response.success?
      response.success?
    end
  end
end
