class TelegramBotSubscriber
  include Rails.application.routes.url_helpers

  def self.subscribe
    ActiveSupport::Notifications.subscribe(/\Asession\.updated\Z/) do |*args|
      new.handle_session_updated(ActiveSupport::Notifications::Event.new(*args))
    end
    ActiveSupport::Notifications.subscribe(/\Asession_speaker\.(?:created|destroyed)\Z/) do |*args|
      new.handle_session_speaker_event(ActiveSupport::Notifications::Event.new(*args))
    end
  end

  def handle_session_updated(event)
    Rails.logger.info("session event #{event.inspect}")
    model_name, action = event.name.split('.')
    record = event.payload[:record]
    changes = event.payload[:changes]

    return unless changes.any? do |attr, (from, to)|
      %w[title language status starts_at ends_at stage_id].include? attr
    end

    if changes["stage_id"]
      changes["stage"] = [Stage.find(changes["stage_id"].first).name, Stage.find(changes["stage_id"].last).name]
      changes.delete("stage_id")
    end

    message = "<b><a href=\"#{conference_session_path(record.conference, record)}\">Session #{record.title}</a> #{action}</b>\n" +
      changes.map { |attr, (from, to)| "- #{attr}: #{from} -> #{to}" }.join("\n") + "\n#{conference_session_path(record.conference, record)}"

    TelegramGroupChatNotificationJob.perform_later(target: "-316096320", text: message, parse_mode: 'HTML')
    # TelegramGroupChatNotificationJob.perform_later(target: "2192297", text: message, parse_mode: 'HTML')
  end

  def handle_session_speaker_event(event)
    Rails.logger.info("session_speaker event #{event.inspect}")
    model_name, action = event.name.split('.')
    record = event.payload[:record]
    session = record.session

    message = "<b><a href=\"#{conference_session_path(session.conference, session)}\">Session #{session.title}</a> Speaker Change</b>\n" +
      "#{record.speaker.name} #{action == 'destroyed' ? 'removed' : 'added'}" + "\n#{conference_session_path(session.conference, session)}"

    TelegramGroupChatNotificationJob.perform_later(target: "-316096320", text: message, parse_mode: 'HTML')
  end
end