# Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/

class Transaction::Notification
  include ChecksHumanChanges

  # Errors of the notification channel itself, as opposed to a problem with one
  #   single message: they will fail for every recipient alike.
  CHANNEL_FAILURE_ERRORS = [
    Channel::XOAuth2RefreshError,
    IOError,
    Net::OpenTimeout,
    Net::ReadTimeout,
    Net::SMTPError,
    OpenSSL::SSL::SSLError,
    SocketError,
    SystemCallError,
  ].freeze

=begin
  {
    object: 'Ticket',
    type: 'update',
    object_id: 123,
    interface_handle: 'application_server', # application_server|websocket|scheduler
    changes: {
      'attribute1' => [before, now],
      'attribute2' => [before, now],
    },
    created_at: Time.zone.now,
    user_id: 123,
  },
=end

  attr_accessor :recipients_and_channels, :recipients_reason

  def initialize(item, params = {})
    @item                    = item
    @params                  = params
    @recipients_and_channels = []
    @recipients_reason       = {}
    @email_channel_failed    = false
  end

  def ticket
    @ticket ||= Ticket.find_by(id: @item[:object_id])
  end

  def article_by_item
    return if !@item[:article_id]

    article = Ticket::Article.find(@item[:article_id])

    # ignore notifications
    sender = Ticket::Article::Sender.lookup(id: article.sender_id)
    if sender&.name == 'System'
      return if @item[:changes].blank? && article.preferences[:notification] != true

      if article.preferences[:notification] != true
        article = nil
      end
    end

    article
  end

  def article
    @article ||= article_by_item
  end

  def current_user
    @current_user ||= User.lookup(id: @item[:user_id]) || User.lookup(id: 1)
  end

  def perform

    # return if we run import mode
    return if Setting.get('import_mode')
    return if %w[Ticket Ticket::Article].exclude?(@item[:object])
    return if @params[:disable_notification]
    return if !ticket

    prepare_recipients_and_reasons

    # Commit the online notifications of all recipients first: every SMTP round
    #   trip would otherwise hold back the online notifications of later recipients.
    notified_recipients = []
    begin
      recipients_and_channels.each do |recipient_settings|
        notified_recipient = ActiveRecord::Base.transaction do
          send_to_single_recipient(recipient_settings)
        end
        notified_recipients.push(notified_recipient) if notified_recipient
      end
    ensure
      # Also after a later recipient failed: the online notifications and daily
      #   locks of these recipients are committed, so no later run sends this email.
      notified_recipients.each { |notified_recipient| deliver_email_and_add_history(**notified_recipient) }
    end
  end

  def prepare_recipients_and_reasons

    # loop through all group users
    possible_recipients = possible_recipients_of_group(ticket.group_id)

    # loop through all mention users
    mention_users = Mention.where(mentionable_type: @item[:object], mentionable_id: @item[:object_id]).map(&:user)
    if mention_users.present?

      # only notify if read permission on group are given
      mention_users.each do |mention_user|
        next if !mention_user.group_access?(ticket.group_id, 'read')

        possible_recipients.push mention_user
        @recipients_reason[mention_user.id] = __('You are receiving this because you were mentioned in this ticket.')
      end
    end

    # apply owner
    if ticket.owner_id != 1
      possible_recipients.push ticket.owner
      @recipients_reason[ticket.owner_id] = __('You are receiving this because you are the owner of this ticket.')
    end

    # apply out of office agents
    possible_recipients_additions = Set.new
    possible_recipients.each do |user|
      ooo_replacements(
        user:         user,
        replacements: possible_recipients_additions,
        reasons:      recipients_reason,
        ticket:       ticket,
      )
    end

    if possible_recipients_additions.present?
      # join unique entries
      possible_recipients |= possible_recipients_additions.to_a
    end

    recipients_reason_by_notifications_settings(possible_recipients)
  end

  def recipients_reason_by_notifications_settings(possible_recipients)
    already_checked_recipient_ids = {}
    possible_recipients.each do |user|
      result = NotificationFactory::Mailer.notification_settings(user, ticket, @item[:type])
      next if !result
      next if already_checked_recipient_ids[user.id]

      already_checked_recipient_ids[user.id] = true
      @recipients_and_channels.push result
      next if recipients_reason[user.id]

      @recipients_reason[user.id] = __('You are receiving this because you are a member of the group of this ticket.')
    end
  end

  def recipient_myself?(user)
    return false if @params[:interface_handle] != 'application_server'
    return true if article&.updated_by_id == user.id
    return true if !article && @item[:user_id] == user.id

    false
  end

  def send_to_single_recipient(recipient_settings)
    user     = recipient_settings[:user]
    channels = recipient_settings[:channels]

    # ignore user who changed it by him self via web
    return if recipient_myself?(user)

    # ignore inactive users
    return if !user.active?

    # ignore if no changes has been done
    changes = human_changes(@item[:changes], ticket, user)
    return if @item[:type] == 'update' && !article && changes.blank?

    # check if today already notified
    if %w[reminder_reached escalation escalation_warning].include?(@item[:type]) && !Ticket::DailyEventLock.lock!(
      lock_type:      'notification',
      lock_activator: @item[:type],
      ticket:,
      related_object: user,
    )
      return
    end

    # create online notification
    used_channels = []

    if channels['online']
      used_channels.push 'online'

      send_to_single_recipient_online(user, ticket, article)
    end

    { user:, channels:, changes:, used_channels: }
  end

  def add_recipient_list_to_history(ticket, user, channels, type)
    return if channels.blank?

    identifier     = user.email.presence || user.login
    recipient_list = "#{identifier}(#{type}:#{channels.join(',')})"

    History.add(
      o_id:           ticket.id,
      history_type:   'notification',
      history_object: 'Ticket',
      value_to:       recipient_list,
      created_by_id:  @item[:user_id] || 1
    )
  end

  private

  def ooo_replacements(user:, replacements:, ticket:, reasons:)
    replacement = user.out_of_office_agent

    return if !replacement

    return if !TicketPolicy.new(replacement, ticket).agent_read_access?

    return if !replacements.add?(replacement)

    reasons[replacement.id] = __('You are receiving this because you are out-of-office replacement for a participant of this ticket.')
  end

  def possible_recipients_of_group(group_id)
    User.group_access(group_id, 'full').sort_by(&:login)
  end

  def deliver_email_and_add_history(user:, channels:, changes:, used_channels:)
    if channels['email'] && user.email.present? && deliver_email(user, ticket, article, changes)
      used_channels.push 'email'
    end

    add_recipient_list_to_history(ticket, user, used_channels, @item[:type])
  # Not re-raised: the daily locks of the remaining recipients are committed, so
  #   they must still get their email, and the dispatcher would only log it too.
  rescue => e
    Rails.logger.error e
  end

  # Deliver the email notification, but never let a broken 'Email::Notification'
  #   channel abort the notification (see #6308): a propagating error would skip
  #   the email and the history entry of all remaining recipients. Any other
  #   error of a single email is contained as well: the daily locks of all
  #   recipients are committed already, so no later run would send their email.
  #
  # Channel#deliver already marked the channel as faulty before raising, so the
  #   misconfiguration stays visible to admins via the channel status. A daily
  #   event lock taken above is kept, just like for the SMTP errors the driver
  #   silences: where the recipient has the online channel enabled, they were
  #   notified, they only lack the email.
  #
  # Returns the delivery result, which is falsy if nothing was sent.
  def deliver_email(user, ticket, article, changes)
    return false if !email_deliverable?(user)

    send_to_single_recipient_email(user, ticket, article, changes)
  rescue Channel::DeliveryError => e
    @email_channel_failed = true if channel_failure?(e)

    Rails.logger.error "Unable to send ticket email notification to #{user.email}: #{e.message}"

    false
  rescue => e
    Rails.logger.error e

    false
  end

  def channel_failure?(error)
    CHANNEL_FAILURE_ERRORS.any? { |klass| error.original_error.is_a?(klass) }
  end

  def email_deliverable?(user)
    # A broken channel fails for every recipient alike, so stop trying after the
    #   first error: an unreachable server costs a connection timeout per
    #   attempt, which would otherwise block this notification for minutes on
    #   end. Problems of a single message do not set this flag.
    if @email_channel_failed
      Rails.logger.info "Send no email notification to #{user.email} because the notification channel failed to deliver before"
      return false
    end

    blocked_in_days = user.mail_delivery_failed_blocked_days
    if blocked_in_days.positive?
      Rails.logger.info "Send no email notification to #{user.email} because email is marked as mail_delivery_failed for #{blocked_in_days} day(s)"
      return false
    end

    true
  end

  def send_to_single_recipient_online(user, ticket, article)
    created_by_id = @item[:user_id] || 1

    # delete old notifications
    if @item[:type] == 'reminder_reached'
      seen = false
      created_by_id = 1
      OnlineNotification.remove_by_type('Ticket', ticket.id, @item[:type], user)

    elsif %w[escalation escalation_warning].include?(@item[:type])
      seen = false
      created_by_id = 1
      OnlineNotification.remove_by_type('Ticket', ticket.id, 'escalation', user)
      OnlineNotification.remove_by_type('Ticket', ticket.id, 'escalation_warning', user)

    # on updates without state changes create unseen messages
    elsif @item[:type] != 'create' && (@item[:changes].blank? || @item[:changes]['state_id'].blank?)
      seen = false
    else
      seen = OnlineNotification.seen_state?(ticket, user.id)
    end

    OnlineNotification.add(
      type:          @item[:type],
      object:        @item[:object],
      o_id:          @item[:object].eql?('Ticket') ? ticket.id : article.id,
      seen:          seen,
      created_by_id: created_by_id,
      user_id:       user.id,
    )
    Rails.logger.debug { "sent ticket online notification to agent (#{@item[:type]}/#{ticket.id}/#{user.email})" }
  end

  def send_to_single_recipient_email(user, ticket, article, changes)
    # get user based notification template
    # if create, send create message / block update messages
    template = case @item[:type]
               when 'create'
                 'ticket_create'
               when 'update'
                 'ticket_update'
               when 'reminder_reached'
                 'ticket_reminder_reached'
               when 'escalation'
                 'ticket_escalation'
               when 'escalation_warning'
                 'ticket_escalation_warning'
               when 'update.merged_into'
                 'ticket_update_merged_into'
               when 'update.received_merge'
                 'ticket_update_received_merge'
               when 'update.reaction'
                 'ticket_article_update_reaction'
               else
                 raise "unknown type for notification #{@item[:type]}"
               end

    attachments = []
    if article
      attachments = article.attachments_inline
    end
    NotificationFactory::Mailer.notification(
      template:    template,
      user:        user,
      objects:     {
        ticket:       ticket,
        article:      article,
        recipient:    user,
        current_user: current_user,
        changes:      changes,
        reason:       recipients_reason[user.id],
      },
      message_id:  "<notification.#{DateTime.current.to_fs(:number)}.#{ticket.id}.#{user.id}.#{SecureRandom.uuid}@#{Setting.get('fqdn')}>",
      references:  ticket.get_references,
      main_object: ticket,
      attachments: attachments,
    ).tap do
      Rails.logger.debug { "sent ticket email notification to agent (#{@item[:type]}/#{ticket.id}/#{user.email})" }
    end
  end
end
