--[[
	Cerebro - Wishlist Module
	Manages player wishlists and priorities
]]--

local AddonName, PrivateTable = ...
local Cerebro = LibStub("AceAddon-3.0"):GetAddon(AddonName)
local Wishlist = Cerebro:NewModule("Wishlist", "AceEvent-3.0")

--[[=============================================
	Wishlist Management
===============================================]]

function Wishlist:AddItem(itemLink, priority, notes)
	local player = Cerebro:GetPlayerFullName()
	local itemID = Cerebro:GetItemIDFromLink(itemLink)

	if not itemID then
		Cerebro:Print("Invalid item link.")
		return false
	end

	-- Validate priority
	priority = tonumber(priority) or 3
	if priority < 1 then priority = 1 end
	if priority > 5 then priority = 5 end

	-- Initialize wishlist if needed
	if not Cerebro.db.global.wishlists[player] then
		Cerebro.db.global.wishlists[player] = {}
	end

	-- Capture current gear for "Replaced Item" tracking
	local replacedLink = nil
	local itemInfo = Cerebro:GetItemInfo(itemLink)
	if itemInfo and itemInfo.equipLoc then
		local slot = Cerebro:GetSlotIDFromEquipLoc(itemInfo.equipLoc)
		if slot then
			local slotID = type(slot) == "table" and slot[1] or slot
			replacedLink = GetInventoryItemLink("player", slotID)
		end
	end

	-- Add or update item
	Cerebro.db.global.wishlists[player][itemID] = {
		priority = priority,
		notes = notes or "",
		addedTime = time(),
		replacedLink = replacedLink,
	}

	Cerebro:Print(string.format("Added to wishlist: %s (Priority: %d)", itemLink, priority))
	return true
end

function Wishlist:RemoveItem(itemLink)
	local player = Cerebro:GetPlayerFullName()
	local itemID = Cerebro:GetItemIDFromLink(itemLink)

	if not itemID then return false end

	if not Cerebro.db.global.wishlists[player] or not Cerebro.db.global.wishlists[player][itemID] then
		Cerebro:Print("Item not found in your wishlist.")
		return false
	end

	Cerebro.db.global.wishlists[player][itemID] = nil
	Cerebro:Print("Removed from wishlist: " .. itemLink)
	return true
end

function Wishlist:GetWishlist(player)
	player = player or Cerebro:GetPlayerFullName()

	if not Cerebro.db.global.wishlists[player] then
		return {}
	end

	local wishlist = {}
	for itemID, data in pairs(Cerebro.db.global.wishlists[player]) do
		table.insert(wishlist, {
			itemID = itemID,
			priority = data.priority,
			notes = data.notes,
			addedTime = data.addedTime,
		})
	end

	table.sort(wishlist, function(a, b)
		if a.priority ~= b.priority then
			return a.priority < b.priority
		else
			return a.addedTime < b.addedTime
		end
	end)

	return wishlist
end
