# frozen_string_literal: true

# Popup service
class NotifyEmailService

  def initialize(dotation_id)
    @dotation_id = dotation_id
  end

  def call
    check_filters
  end

  private

  def check_filters
    filter_for_emails = FilterForEmail.all
    filter_for_emails.each do |filter_for_email|
      hsh = filter_for_email.filters.transform_keys(&:to_sym)
      dot = Dotation.search_with_filters(hsh)
                    .by_id(@dotation_id).public_dot.first
      next if dot.blank?

      sef =
        SentEmailFilter.by_dotation(dot.id).by_filter(filter_for_email.id).first

      next unless sef.blank?

      SentEmailFilter.create(filter_for_email_id: filter_for_email.id,
                             dotation_id: dot.id)
      NewDotationMailer.with(dotation_id: dot.id,
                             email_filter: filter_for_email.id)
                       .notification_email.deliver
    end
  end
end
