local _, ns = ...

local DATA = ns.Data or {}
local MID_UTILITY_UPGRADE_CRESTS = DATA.MID_UTILITY_UPGRADE_CRESTS or {}
local MID_UTILITY_RESOURCE_ENTRIES = DATA.MID_UTILITY_RESOURCE_ENTRIES or {}

ns.MID_UPGRADE_CRESTS = MID_UTILITY_UPGRADE_CRESTS
ns.MID_RESOURCE_ENTRIES = MID_UTILITY_RESOURCE_ENTRIES

local WoWApi = ns.WoWApi or {}
local getCurrencyInfoByID = WoWApi.GetCurrencyInfoByID
local getItemCountByID = WoWApi.GetItemCountByID

local getUtilityEntryKey
local buildCurrencyUtilityRecord
local buildItemUtilityRecord

getUtilityEntryKey = function(entry)
    if type(entry) ~= "table" then
        return nil
    end

    if entry.currencyID then
        return "currency:" .. tostring(entry.currencyID)
    end

    if entry.itemID then
        return "item:" .. tostring(entry.itemID)
    end

    return nil
end

buildCurrencyUtilityRecord = function(currencyID)
    local info = getCurrencyInfoByID(currencyID)
    if not info then
        return nil
    end

    return {
        currencyID = currencyID,
        name = info.name or ("Currency " .. tostring(currencyID)),
        icon = info.iconFileID or info.icon,
        quantity = math.max(0, tonumber(info.quantity) or 0),
    }
end

buildItemUtilityRecord = function(itemID)
    if not itemID or itemID <= 0 then
        return nil
    end

    local name = C_Item and C_Item.GetItemNameByID and C_Item.GetItemNameByID(itemID) or nil
    local icon = C_Item and C_Item.GetItemIconByID and C_Item.GetItemIconByID(itemID) or nil

    return {
        itemID = itemID,
        name = name or ("Item " .. tostring(itemID)),
        icon = icon,
        quantity = getItemCountByID(itemID),
    }
end

function ns:BuildCurrentCharacterUtilityState()
    local state = {
        updatedAt = time(),
        upgrades = {},
        resources = {},
    }

    for _, currencyID in ipairs(MID_UTILITY_UPGRADE_CRESTS) do
        state.upgrades[tostring(currencyID)] = buildCurrencyUtilityRecord(currencyID)
    end

    for _, entry in ipairs(MID_UTILITY_RESOURCE_ENTRIES) do
        local key = getUtilityEntryKey(entry)
        if key then
            if entry.currencyID then
                state.resources[key] = buildCurrencyUtilityRecord(entry.currencyID)
            elseif entry.itemID then
                state.resources[key] = buildItemUtilityRecord(entry.itemID)
            end
        end
    end

    return state
end

function ns:RefreshCurrentCharacterUtilityData()
    local record = self:RefreshCurrentCharacterRecord()
    record.utility = self:BuildCurrentCharacterUtilityState()
    return record.utility
end

function ns:GetCharacterUtilityState(keyOrCharacter)
    local key = keyOrCharacter
    if type(keyOrCharacter) == "table" then
        key = keyOrCharacter.key
    end

    local record = self:GetStoredCharacterRecord(key, false)
    return type(record) == "table" and type(record.utility) == "table" and record.utility or nil
end
