# frozen_string_literal: true

module Ticket::Article::EnqueueCommunicateCdrWhatsappJob
  extend ActiveSupport::Concern

  included do
    after_create :ticket_article_enqueue_communicate_cdr_whatsapp_job
  end

  private

  def ticket_article_enqueue_communicate_cdr_whatsapp_job
    # return if we run import mode
    return true if Setting.get('import_mode')

    # if sender is customer, do not communicate
    return true unless sender_id

    sender = Ticket::Article::Sender.lookup(id: sender_id)
    return true if sender.nil?
    return true if sender.name == 'Customer'

    # only apply on cdr whatsapp messages
    return true unless type_id

    type = Ticket::Article::Type.lookup(id: type_id)
    return true unless type.name.match?(/\Acdr_whatspp/i)

    CommunicateCdrWhatsappJob.perform_later(id)
  end
end
