class LnAggregateData
  include Mongoid::Document

  field :ln, type: Integer
  field :org_id, type: Integer
  field :hr, type: Array, default: [] #=> [{'h' => 23, 'tx_r' => 0, 'rx_r' => 0, 'tx_u' => 0, 'rx_u' => 0, 'a_av' => 0, 'a_mi' => 0, 'a_mx' => 0}....]
  field :d, type: Date
  field :c_count, type: Integer # connected clients count per network
  field :c_tx_u, type: Integer # connected clients tx usage
  field :c_tx_r, type: Integer # connected clients tx rate
  field :c_rx_u, type: Integer # connected clients rx usage
  field :c_rx_r, type: Integer # connected clients rx rate

  index({ "ln" => 1, "d" => 1 }, { background: true })

  def self.save_hourly_data(st, ln_id, hourly = true)
    col = hourly ? MonitoringDataCapped : MonitoringChild
  
    aggregate_data = col.collection.aggregate({ "$match" => { "ln_id" => { "$in" => ln_id },
                                                              "created_at" => { "$gte" => st.utc, "$lt" => (st + 1.hour).utc } } },
                                                { "$project" => { "ln_id" => 1,
                                                                  "org_id" => 1,
                                                                  "uplink" => { "$ifNull" => ["$uplink", "$lan"] } } },
                                                { "$unwind" => "$uplink" },
                                                { "$project" => { 'ln' => "$ln_id",
                                                                  "org_id" => 1,
                                                                  "tx_u" => "$uplink.TX_BYTES_INT",
                                                                  "tx_r" => "$uplink.TX_RATE",
                                                                  "rx_u" => "$uplink.RX_BYTES_INT",
                                                                  "rx_r" => "$uplink.RX_RATE" } },
                                                { "$group" => { "_id" => { "ln" => "$ln", "org_id" => "$org_id" },
                                                               "tx_u" => { "$sum" => "$tx_u" },
                                                                "tx_r" => { "$avg" => "$tx_r" },
                                                                "rx_u" => { "$sum" => "$rx_u" },
                                                                "rx_r" => { "$avg" => "$rx_r" } } },
                                                { "$project" => { "_id" => 1,
                                                                  "tx_u" => 1,
                                                                  "tx_r" => 1,
                                                                  "rx_u" => 1,
                                                                  "rx_r" => 1,
                                                } })
  
    aggregate_clients_count = col.collection.aggregate([
                                                         { "$match" => { "ln_id" => { "$in" => ln_id },
                                                                         "created_at" => { "$gte" => st.utc, "$lt" => (st + 1.hour).utc } } },
                                                         { "$project" => { "ln_id" => 1, "clients" => { "$ifNull" => ["$clients", []] } } },
                                                         { "$unwind" => "$clients" },
                                                         { "$project" => { 'ln' => "$ln_id",
                                                                           "c_tx_u" => "$clients.TX_BYTES_INT",
                                                                           "c_tx_r" => "$clients.TX_RATE",
                                                                           "c_rx_u" => "$clients.RX_BYTES_INT",
                                                                           "c_rx_r" => "$clients.RX_RATE",
                                                                           "MAC" => "$clients.MAC" } },
                                                         { "$group" => { "_id" => "$ln",
                                                                         "uniqueMacs" => { "$addToSet" => "$MAC" },
                                                                         "c_tx_u" => { "$sum" => "$c_tx_u" },
                                                                         "c_tx_r" => { "$avg" => "$c_tx_r" },
                                                                         "c_rx_u" => { "$sum" => "$c_rx_u" },
                                                                         "c_rx_r" => { "$avg" => "$c_rx_r" } } },
                                                         { "$project" => { "_id" => 1,
                                                                           "c_count" => { "$size" => "$uniqueMacs" },
                                                                           "c_tx_u" => 1,
                                                                           "c_tx_r" => 1,
                                                                           "c_rx_u" => 1,
                                                                           "c_rx_r" => 1 } }
                                                       ])
  
    # Convert client counts into a hash for quick lookup
    client_count_hash = aggregate_clients_count.each_with_object({}) do |doc, hash|
      hash[doc['_id']] = doc
    end
  
    aggregate_data.each do |data|
      ln_id = data['_id']['ln']
      org_id = data['_id']['org_id']
  
      client_data = client_count_hash[ln_id] || {}
  
      hr_entry = {
        'h' => st.hour,
        'tx_r' => data['tx_r'],
        'tx_u' => data['tx_u'],
        'rx_r' => data['rx_r'],
        'rx_u' => data['rx_u'],
        'c_count' => client_data['c_count'] || 0,
        'c_tx_u' => client_data['c_tx_u'] || 0,
        'c_tx_r' => client_data['c_tx_r'] || 0,
        'c_rx_u' => client_data['c_rx_u'] || 0,
        'c_rx_r' => client_data['c_rx_r'] || 0,
      }
  
      self.collection.where({ "ln" => ln_id, "org_id" => org_id, "d" => st.to_date })
          .update(
            { "$push" => { "hr" => hr_entry } },
            upsert: true
          )
    end
  end
  
      
  def self.save_dynamic_data(st, ln_ids, interval)
    puts "Inside save_dynamic_data with interval: #{interval}, start time: #{st}, ln_ids: #{ln_ids}"
    DynamicModelGenerator.create_model(interval)
    class_name = "Ln#{interval.capitalize}Data"
    model_class = Object.const_get(class_name)
    col = MonitoringChild
    slot_start, slot_end = get_time_range_for_interval(st, interval)
    puts "Slot time range: #{slot_start} - #{slot_end}"

    Array(ln_ids).each do |ln_id|
      puts "Processing Location Network ID: #{ln_id}"
      location_network = LocationNetwork.find_by(id: ln_id)
      network_name = location_network.network_name
      template_id = location_network.cloned_network_id
      template_name = LocationNetwork.find_by(id: template_id).try(:network_name) || ''
      organisation = location_network.organisation
      organisation_id = organisation.id
      puts "Organisation ID: #{organisation_id}"
      router_inventories = location_network.router_inventories.joins(hardware_part: :hardware_category)
      mac_ids = location_network.router_inventories.pluck(:mac_id)
      # total_count_by_category = router_inventories.group('hardware_categories.name').count
      isp = $redis.hget("LN:#{ln_id}", "isp")

      device_details = {
        switch: { total: 0, up: 0, down: 0, dor: 0 },
        access_point: { total:  0, up: 0, down: 0, dor: 0 },
        router: { total:  0, up: 0, down: 0, dor: 0 }
      }

      timezone = location_network.timezone
      health_slot = slot_end.in_time_zone(timezone)
      hour_completed = (slot_end.min == 0)

      existing_data = model_class.collection.find({ "ln" => ln_id, "org_id" => organisation_id }).first
      last_24_health = existing_data && existing_data["last_24_health"] ? existing_data["last_24_health"] : []

      if last_24_health.empty?
        puts "First time run detected! Populating last_24_health with last 24 hourly slots."
        nor_dormant_mac_ids = filter_nor_dormant_mac_ids(mac_ids, organisation)
      
        last_24_health = (0..23).map do |h_offset|
          hour_time = health_slot - (23 - h_offset).hours
      
          hour_time = hour_time.beginning_of_hour.to_i - 1.hour
        
          uptime_percentages = nor_dormant_mac_ids.map do |mac_id|
            RouterInventory.calculate_downtime(mac_id, hour_time, hour_time + 1.hour, 3600).sum do |interval|
              interval[:up_per]
            end
          end.sum
      
          {
            time: hour_time,
            health: uptime_percentages > 0 ? (uptime_percentages / nor_dormant_mac_ids.size.to_f).round(1) : 0
          }
        end
      elsif hour_completed
        # Regular hourly update
        new_hourly_slot = health_slot.beginning_of_hour.to_i - 1.hour
      
      if(last_24_health.last[:time] != new_hourly_slot)
        # Remove the oldest entry if we already have 24 slots
        last_24_health.shift if last_24_health.size >= 24
      
        nor_dormant_mac_ids = filter_nor_dormant_mac_ids(mac_ids)
      
        uptime_percentages = nor_dormant_mac_ids.map do |mac_id|
          RouterInventory.calculate_downtime(mac_id, new_hourly_slot, new_hourly_slot + 1.hour, 3600).sum do |interval|
            interval[:up_per]
          end
        end.sum
      
        last_24_health << {
          time: new_hourly_slot,
          health: uptime_percentages > 0 ? (uptime_percentages / nor_dormant_mac_ids.size.to_f).round(1) : 0
        }
      
        puts "Added new hourly entry to last_24_health."
      end
    end
      

    overall_health_last24hr = last_24_health.sum { |entry| entry[:health] } / 24.0

      switch_model = {}
      ap_model = {}

      # query to aggregate uplink data
      uplink_data = col.collection.aggregate([
        { "$match" => {
            "ln_id" => ln_id,
            "created_at" => { "$gte" => slot_start.utc, "$lt" => slot_end.utc }
          }
        },
        { "$project" => {
            "ln_id" => 1,
            "org_id" => 1,
            "nasid" => "$info.NASID",
            "uplink" => { "$ifNull" => ["$uplink", "$lan"] }  # Ensures uplink is not null
          }
        },
        { "$project" => {
            "ln_id" => 1,
            "org_id" => 1,
            "nasid" => 1,
            "uplink" => {
              "$cond" => { "if" => { "$eq" => ["$uplink", nil] }, "then" => [], "else" => "$uplink" }
            }
          }
        },
        { "$unwind" => { "path" => "$uplink", "preserveNullAndEmptyArrays" => true } },  # Keeps empty uplink
        { "$project" => {
            'ln' => "$ln_id",
            'org_id' => "$org_id",
            "nasid" => "$nasid",
            "tx_u" => "$uplink.TX_BYTES_INT",
            "tx_r" => "$uplink.TX_RATE",
            "rx_u" => "$uplink.RX_BYTES_INT",
            "rx_r" => "$uplink.RX_RATE"
          }
        },
        { "$group" => {
            "_id" => "$ln",
            "org_id" => { "$last" => "$org_id" },
            "nasid" => { "$last" => "$nasid" },
            "tx_u" => { "$sum" => "$tx_u" },
            "tx_r" => { "$avg" => "$tx_r" },
            "rx_u" => { "$sum" => "$rx_u" },
            "rx_r" => { "$avg" => "$rx_r" }
          }
        }
      ]).to_a
      

      client_data = col.collection.aggregate([
                  { "$match" => {
                    "ln_id" => ln_id,
                      "created_at" => { "$gte" => slot_start.utc, "$lt" => slot_end.utc }
                    }
                  },
                  { "$project" => {
                      "ln_id" => 1,
                      "clients" => { "$ifNull" => ["$clients", []] }  
                    }
                  },
                  { "$unwind" => { "path" => "$clients", "preserveNullAndEmptyArrays" => true } },  
                  { "$project" => {
                      "ln" => "$ln_id",
                      "tx_u" => "$clients.TX_BYTES_INT",
                      "tx_r" => "$clients.TX_RATE",
                      "rx_u" => "$clients.RX_BYTES_INT",
                      "rx_r" => "$clients.RX_RATE",
                      "MAC" => "$clients.MAC",
                      "type" => "$clients.TYPE"
                    }
                  },
                  { "$group" => {
                      "_id" => "$ln",
                      "tx_u" => { "$sum" => "$tx_u" },  
                      "tx_r" => { "$avg" => "$tx_r" },
                      "rx_u" => { "$sum" => "$rx_u" },
                      "rx_r" => { "$avg" => "$rx_r" },
                      "uniqueMacs" => { "$addToSet" => "$MAC" },
                      "wiredMacs" => { "$addToSet" => { "$cond" => [{"$eq" => ["$type", "1"]}, "$MAC", nil] } },
                      "wirelessMacs" => { "$addToSet" => { "$cond" => [{ "$eq" => ["$type", "2"] }, "$MAC", nil] } }
                    }
                  }
                ]).to_a

    wired_clients = wireless_clients = 0

    if client_data.any?
     wired_macs = client_data[0]['wiredMacs'].compact
     wireless_macs = client_data[0]['wirelessMacs'].compact
      
     wired_macs = wired_macs - wireless_macs
     wired_clients = wired_macs.size
     wireless_clients = wireless_macs.size
    end

      managed_clients = ClientDevice.collection.aggregate([
        { "$match" => {  "ln_id" => ln_id, "is_blocked" => false } },  
        { "$group" => {
            "_id" => "$ln_id",
            "managed_clients" => { "$addToSet" => "$mac" }  
          }
        },
        { "$project" => {
            "_id" => 1,
            "managed_clients" => 1,  # Retain the MAC addresses array
            "managed_clients_count" => { "$size" => "$managed_clients" }  
          }
        }
      ]).to_a

      client_macs = managed_clients.any? ? managed_clients.first['managed_clients'] : []

      managed_clients_count = managed_clients.any? ? managed_clients.first['managed_clients_count'] : 0
      
      lan_wireless_count = col.collection.aggregate([
                                                      { "$match" => {
                                                        "ln_id" => ln_id,
                                                        "created_at" => { "$gte" => slot_start.utc, "$lt" => slot_end.utc }
                                                      } },
                                                      { "$project" => {
                                                        "ln_id" => 1,
                                                        "clients" => { "$ifNull" => ["$clients", []] }
                                                      } },
                                                      { "$unwind" => "$clients" },
                                                      { "$match" => { 
                                                          "clients.MAC" => { "$in" => client_macs }  # filter for client_macs 
                                                        } },
                                                      { "$project" => {
                                                        'ln' => "$ln_id",
                                                        "MAC" => "$clients.MAC",
                                                        "type" => "$clients.TYPE"
                                                      } },
                                                      { "$group" => {
                                                        "_id" => "$MAC",
                                                        "wired" => { "$first" => { "$cond" => [{ "$eq" => ["$type", "1"] }, 1, 0] } },
                                                        "wireless" => { "$first" => { "$cond" => [{ "$eq" => ["$type", "2"] }, 1, 0] } }
                                                      } },
                                                      { "$group" => {
                                                        "_id" => nil,
                                                        "uniqueMacs" => { "$addToSet" => "$_id" },
                                                        "wired" => { "$sum" => "$wired" },
                                                        "wireless" => { "$sum" => "$wireless" }
                                                      } }
                                                    ]).to_a

      lan_count = lan_wireless_count.any? ? lan_wireless_count.first['wired'] : 0
      wireless_count = lan_wireless_count.any? ? lan_wireless_count.first['wireless'] : 0
      down_clients = [managed_clients_count - (lan_count + wireless_count), 0].max
      puts "LAN count: #{lan_count}, Wireless count: #{wireless_count}, Down clients: #{down_clients}"

      combined_data = {
        ln: ln_id,
        nasid: uplink_data.any? ? uplink_data[0]['nasid'] : 0,
        org_id: uplink_data.any? ? uplink_data[0]['org_id'] : 0,
        tx_u: uplink_data.any? ? uplink_data[0]['tx_u'] : 0,
        tx_r: uplink_data.any? ? uplink_data[0]['tx_r'] : 0,
        rx_u: uplink_data.any? ? uplink_data[0]['rx_u'] : 0,
        rx_r: uplink_data.any? ? uplink_data[0]['rx_r'] : 0,
        clients: {
          count: client_data.any? ? client_data[0]['uniqueMacs'].size : 0,
          tx_u: client_data.any? ? client_data[0]['tx_u'] : 0,
          tx_r: client_data.any? ? client_data[0]['tx_r'] : 0,
          rx_u: client_data.any? ? client_data[0]['rx_u'] : 0,
          rx_r: client_data.any? ? client_data[0]['rx_r'] : 0,
          wired: wired_clients,
          wireless: wireless_clients
        },
        managed_clients_count: managed_clients_count,
        lan_count: lan_count,
        wireless_count: wireless_count,
        down_clients: down_clients
      }

      # active uplinks  => {
      #   "1" => { "type" => "1", "is_primary" => true, "status" => "active" },
      #   "4" => { "type" => "4", "is_primary" => nil, "status" => "down" }
      # }

      uplink_info_array = []
      grouped_uplinks = {}
      networks_affected = 0
      primary_uplink_down = false

      up_mac_ids = RouterInventory.find_up_list(mac_ids, RouterInventory.get_hb_intreval(location_network.hb_freq))
      

      wan_cell_count = 0
      organisation = location_network.organisation
      dor_router_macs = []
      up_router_macs = []
      router_inventories.each do |inventory|
        category = inventory.hardware_part.hardware_category.name
        part_name = inventory.hardware_part.name

        if category == 'switch'
          switch_model[part_name] ||= { up: 0, down: 0 }
        end

        if category == 'access_point'
          ap_model[part_name] ||= { up: 0, down: 0 }
        end

        last_hb = $redis.hgetall("AP:#{inventory.mac_id}")["last_hb"]
        dormant_days = organisation.organisation_settings["dormant_days"] || 7
        last_hb_time = last_hb.to_i
        current_time = Time.now.to_i

        if up_mac_ids.include?(inventory.mac_id)
          device_details[category.to_sym][:up] += 1
          switch_model[part_name][:up] += 1 if category == 'switch'
          ap_model[part_name][:up] += 1 if category == 'access_point'
        elsif last_hb.blank? || current_time - last_hb_time > dormant_days * 86400
          device_details[category.to_sym][:dor] += 1
          dor_router_macs << inventory.mac_id if category == 'router'
        else
          device_details[category.to_sym][:down] += 1
          switch_model[part_name][:down] += 1 if category == 'switch'
          ap_model[part_name][:down] += 1 if category == 'access_point'
        end

        if category == 'router'
          redis_data = $redis.hgetall("AP:#{inventory.mac_id}")
          next unless redis_data["uplinks"]
      
          # Parse uplinks (default all to inactive)
          uplinks = JSON.parse(redis_data["uplinks"]) rescue {}
          active_uplinks = JSON.parse(redis_data["active_uplinks"]) rescue {}
      
          uplinks.each do |uplink_id, uplink_details|
            uplink_info = {}
      
            uplink_info[uplink_id] = [
              uplink_details["type"],
              uplink_details["is_primary"] == true,
              "inactive" # Default status
            ]
      
            uplink_info_array << uplink_info
      
            if uplink_details["type"]
              grouped_uplinks[uplink_details["type"]] ||= []
              grouped_uplinks[uplink_details["type"]] = [
                uplink_details["is_primary"] == true,
                "inactive"
              ]
            end
          end
      
          # Only update status if the device is up
          if up_mac_ids.include?(inventory.mac_id)
            active_uplinks.each do |uplink_id, uplink_details|
              uplink_info_array.each do |uplink_info|
                if uplink_info[uplink_id]
                  uplink_info[uplink_id][2] =
                    if uplink_id == redis_data["curr_active_uplink"]
                      "active"
                    else
                      uplink_details["status"] == "active" ? "ready" : "inactive"
                    end
                end
              end
      
              if grouped_uplinks[uplink_details["type"]]
                grouped_uplinks[uplink_details["type"]][1] =
                  if uplink_id == redis_data["curr_active_uplink"]
                    "active"
                  else
                    uplink_details["status"] == "active" ? "ready" : "inactive"
                  end
              end
      
              #cellular uplinks
              wan_cell_count += 1 if uplink_details["type"] == "4" && uplink_id == redis_data["curr_active_uplink"]
      
              # Check primary uplink status
              if uplink_details["is_primary"]
                primary_uplink_down = true if uplink_id != redis_data["curr_active_uplink"] || uplink_details["status"] != "active"
              end
            end
          end
      
          up_router_macs << inventory.mac_id
          puts "Uplink info collected for LN #{ln_id}"
        end

      end

      puts "Final device details for LN #{ln_id}: #{device_details}"

      if(up_router_macs.count > 0)
        lan_port_used_routers = col.collection.aggregate([
                              {
                                "$match" => {
                                  "info.NASID" => { "$in" => up_router_macs },
                                  "created_at" => { "$gte" => slot_start.utc, "$lt" => slot_end.utc },
                                  "sw_prt" => { "$exists" => true, "$ne" => [] } 
                                }
                              },
                              {"$group" => {"_id" => "$info.NASID", "sw_prt" => {"$last" => "$sw_prt"}}},
                              {"$project" => {"sw_prt" => 1, "NASID" => "$_id"}},
                              {"$unwind" => "$sw_prt"},
                              {"$match" => {"sw_prt.NO" => {"$ne" => "0"},"sw_prt.ST" => 'up'}},
                              {"$group" => {"_id" => "$NASID", "count" => {"$sum" => 1}}},
                            ]).to_a
                                                      
        puts "lan_port_used_routers :: #{lan_port_used_routers}"
        lan_unused = lan_port_used_routers.any? ? (up_router_macs.count - lan_port_used_routers.count) : 0
        combined_data[:lan_unused] = lan_unused
        puts "LAN unused count: #{lan_unused}"
      else
        combined_data[:lan_unused] = 0
      end

      primary_uplink_status = nil

      grouped_uplinks.each do |uplink_type, uplink_values|
        is_primary = uplink_values[0]  
        status = uplink_values[1]     

        if is_primary
          primary_uplink_status = (status == "active" ? 1 : 0)
          break  
        end
      end

      networks_affected += 1 if primary_uplink_down

      device_details.each do |_, category|
        category[:total] = category[:up] + category[:down] 
      end

      total_devices = device_details.values.sum { |category| category[:up] + category[:down] }

      total_up_devices = device_details.values.sum { |category| category[:up] }

      percentage_up = (total_up_devices.to_f / total_devices) * 100

      only_dormant = false
      device_details.values.each do |category|
        if category[:dor] > 0 && category[:up] == 0 && category[:down] == 0
          only_dormant = true
        elsif category[:up] > 0 || category[:down] > 0
          only_dormant = false
          break
        end
      end

      all_down_devices = device_details.values.reject { |category| category[:total] == 0 }.all? { |category| category[:up] == 0 && category[:down] > 0 }
      
      network_status = location_network.get_network_status(percentage_up, only_dormant, all_down_devices)

      puts "Network status for LN #{ln_id}: #{network_status}"

      slot_data = {
        st: st.to_i,
        tx_u: combined_data[:tx_u],
        tx_r: combined_data[:tx_r],
        rx_u: combined_data[:rx_u],
        rx_r: combined_data[:rx_r],
        clients: combined_data[:clients],
        managed_clients_count: combined_data[:managed_clients_count],
        lan_count: combined_data[:lan_count],
        wireless_count: combined_data[:wireless_count],
        down_clients: combined_data[:down_clients],
        lan_unused: combined_data[:lan_unused],
        device_details: device_details,
        switch_model: switch_model,
        ap_model: ap_model,
        grouped_uplinks: grouped_uplinks,
        isp: isp,
        wan_cell_count: wan_cell_count,
        status: network_status,
        networks_affected: networks_affected,
        uplink_info_array: uplink_info_array,
        network_name: network_name,
        template_name: template_name,
        overall_health_last24hr: overall_health_last24hr,
        primary_uplink_status: primary_uplink_status
      }

      slot_data["last_24_health"] = last_24_health
      
      puts "Saving data for LN #{ln_id} with slot_data: #{slot_data}"

      model_class.collection.where({ "ln" => ln_id, "org_id" => organisation_id })
                 .update(
                   { "$set" => slot_data },
                   upsert: true
                 )
      
      puts "Data saved for LN #{ln_id}"
    end
  end

  def lns_throughput lns, sd, ed
    if ed - sd < 2.days
      group_by = { "h" => "$hr.h", "d" => { "$dayOfMonth" => "$d" } }
    else
      group_by = { "d" => { "$dayOfMonth" => "$d" } }
    end

    LnAggregateData.collection.aggregate({ "$match" => { "ln" => { "$in" => lns }, "d" => { "$gte" => sd, "$lt" => ed } } }, { "$project" => { "ln" => 1, "hr.h" => 1, "hr.tx_r" => 1, "hr.rx_r" => 1, "d" => 1 } }, { "$unwind" => "$hr" }, { "$group" => { "_id" => group_by, "tx" => { "$avg" => "$hr.tx_r" }, "rx" => { "$avg" => "$hr.rx_r" } } }, { "$sort" => { "_id.d" => 1 } })
  end
  

  def self.get_time_range_for_interval(st, interval)
    case interval.downcase
    when "5m"
      slot_end = st
      slot_start = st - 5.minutes
    when "1h"
      slot_end = st
      slot_start = st - 1.hour
    when "2h"
      slot_end = st
      slot_start = st - 2.hours
    when "1d"
      slot_end = st
      slot_start = st - 1.day
    when "1w"
      slot_end = st
      slot_start = st - 1.week
    when "1m"
      slot_end = st
      slot_start = st - 1.month
    when "1y"
      slot_end = st
      slot_start = st - 1.year
    else
      raise "Unsupported interval: #{interval}"
    end

    return slot_start, slot_end
  end

  def self.filter_nor_dormant_mac_ids(mac_ids, organisation = nil)
    ris = RouterInventory.where(mac_id: mac_ids).all
    ris.reject do |inventory|
      #inventory = RouterInventory.find_by(mac_id: mac_id)
      last_hb = $redis.hgetall("AP:#{inventory.mac_id}")["last_hb"]
      #organisation = inventory ? Organisation.find_by(id: inventory.organisation_id) : nil
      dormant_days = organisation ? (organisation.organisation_settings["dormant_days"] || 7) : 7
      last_hb_time = last_hb.to_i
      current_time = Time.now.to_i
  
      last_hb.nil? || last_hb.empty? || (current_time - last_hb_time > dormant_days * 86400)
    end.map(&:mac_id)
  end

end
