# frozen_string_literal: true

class Channel
  class Driver
    class CdrWhatsapp
      def fetchable?(_channel)
        false
      end

      def disconnect; end

      #
      #       instance = Channel::Driver::CdrWhatsapp.new
      #       instance.send(
      #         {
      #           adapter: 'cdr_whatsapp',
      #           auth: {
      #             api_key:       api_key
      #           },
      #         },
      #         whatsapp_attributes,
      #         notification
      #       )
      #

      def send(options, article, _notification = false)
        # return if we run import mode
        return if Setting.get('import_mode')

        options = check_external_credential(options)

        Rails.logger.debug { 'whatsapp send started' }
        Rails.logger.debug { options.inspect }
        @whatsapp = ::CdrWhatsapp.new(options[:bot_endpoint], options[:bot_token])
        @whatsapp.from_article(article)
      end

      def self.streamable?
        false
      end

      private

      def check_external_credential(options)
        if options[:auth] && options[:auth][:external_credential_id]
          external_credential = ExternalCredential.find_by(id: options[:auth][:external_credential_id])
          raise "No such ExternalCredential.find(#{options[:auth][:external_credential_id]})" unless external_credential

          options[:auth][:api_key] = external_credential.credentials['api_key']
        end
        options
      end
    end
  end
end
