module Sessions
  class Resume
    def initialize(session)
      @session = session
    end

    def call
      unless @session.paused?
        raise Teams::EntitlementError.new("La sessione non è in pausa", code: "not_paused")
      end

      cancel_timeout_job
      @session.begin_connect! if @session.may_begin_connect?
      log_event("resumed")
      SessionChannel.broadcast_message(@session, { type: "command", action: "resume_stream" })
      @session
    end

    private

    def cancel_timeout_job
      return if @session.timeout_job_id.blank?

      Sidekiq::ScheduledSet.new.find_job(@session.timeout_job_id)&.delete
      @session.update!(timeout_job_id: nil)
    end

    def log_event(type)
      @session.stream_events.create!(event_type: type, occurred_at: Time.current, metadata: {})
    end
  end
end
