local DR = select(2, ...)

--- Auto-populates roll sessions from loot: when the raid leader opens a loot
--- window, every item at or above the configured quality automatically gets
--- its own session. Manual linking via the leader window still works.
local LootWatcher = {
  recentlyAdded = {},
}
LibStub("AceEvent-3.0"):Embed(LootWatcher)

-- Don't re-open a session if the same item link was auto-added recently
-- (re-opening the same loot window, multiple lootable corpses, etc.).
local DEDUP_SECONDS = 600

local function now()
  return GetServerTime and GetServerTime() or time()
end

function LootWatcher:ScanLoot()
  if not DR.db.profile.autoAddLoot then
    return
  end
  if not (GetNumLootItems and GetLootSlotLink and GetLootSlotInfo) then
    return
  end

  -- Only in raids designated via the activation prompt (or test mode).
  if not DR:Require("Modules.RaidActivation"):IsActive() then
    return
  end

  local manager = DR:Require("Services.SessionManager")
  if not manager:IsRaidLeaderAuthority() then
    return
  end
  -- Solo looting outside test mode would open sessions for every world epic.
  if not IsInGroup() and not DR.Runtime.testMode then
    return
  end

  local minQuality = tonumber(DR.db.profile.autoAddLootMinQuality) or 4
  local numItems = GetNumLootItems() or 0

  for slot = 1, numItems do
    local slotOk, link = pcall(GetLootSlotLink, slot)
    if slotOk and link then
      local infoOk, _, _, _, _, quality = pcall(GetLootSlotInfo, slot)
      if infoOk and (quality or 0) >= minQuality then
        local ts = self.recentlyAdded[link]
        if not ts or (now() - ts) > DEDUP_SECONDS then
          self.recentlyAdded[link] = now()
          local ok, reason, extra = manager:OpenSession(link)
          if ok then
            DR:Print("Loot session auto-added: " .. link)
          elseif reason == "version_gate" then
            DR:Print("Auto-add blocked by version gate: " .. table.concat(extra or {}, ", "))
          end
        end
      end
    end
  end
end

function LootWatcher:OnInitialize()
  self.recentlyAdded = {}
  self:RegisterEvent("LOOT_OPENED", function()
    self:ScanLoot()
  end)
end

DR:RegisterModule("Modules.LootWatcher", LootWatcher)
