local _, ns = ...

local Util = ns.Util or {}
local getWeeklyResetInfo = Util.GetWeeklyResetInfo

local WeeklyMemory = ns.WeeklyMemory or {}
ns.WeeklyMemory = WeeklyMemory

local function getCurrentWeeklyMemoryKey()
    local _, weeklyResetAt = getWeeklyResetInfo()
    local weekKey = tonumber(weeklyResetAt)
    if not weekKey or weekKey <= 0 then
        return nil
    end

    return tostring(weekKey)
end

local function getWeeklyMemoryBucket(bucketKey)
    if type(bucketKey) ~= "string" or bucketKey == "" then
        return nil
    end

    local currentInfo = ns and ns.GetCurrentCharacterInfo and ns:GetCurrentCharacterInfo() or nil
    local characterKey = currentInfo and currentInfo.key or nil
    local weekKey = getCurrentWeeklyMemoryKey()
    if not characterKey or not weekKey then
        return nil
    end

    ns.db = ns.db or {}
    ns.db.weeklyMemory = ns.db.weeklyMemory or {}
    ns.db.weeklyMemory[bucketKey] = ns.db.weeklyMemory[bucketKey] or {}
    ns.db.weeklyMemory[bucketKey][characterKey] = ns.db.weeklyMemory[bucketKey][characterKey] or {}
    ns.db.weeklyMemory[bucketKey][characterKey][weekKey] = ns.db.weeklyMemory[bucketKey][characterKey][weekKey] or {}

    return ns.db.weeklyMemory[bucketKey][characterKey][weekKey]
end

local function getRememberedWeeklyMemory(bucketKey)
    local weekKey = getCurrentWeeklyMemoryKey()
    local bucket = ns.db
        and type(ns.db.weeklyMemory) == "table"
        and ns.db.weeklyMemory[bucketKey]
        or nil
    if not weekKey or type(bucket) ~= "table" then
        return nil
    end

    for characterKey, weeks in pairs(bucket) do
        local memory = type(weeks) == "table" and weeks[weekKey] or nil
        if type(memory) == "table" and memory.completed == true then
            return memory, characterKey
        end
    end

    return nil
end

local function rememberWeeklyCompletion(bucketKey, questID)
    local memory = getWeeklyMemoryBucket(bucketKey)
    if type(memory) ~= "table" then
        return
    end

    memory.completed = true
    memory.questID = tonumber(questID) or memory.questID
    memory.completedAt = memory.completedAt or time()
end

WeeklyMemory.GetCurrentWeeklyMemoryKey = getCurrentWeeklyMemoryKey
WeeklyMemory.GetWeeklyMemoryBucket = getWeeklyMemoryBucket
WeeklyMemory.GetRememberedWeeklyMemory = getRememberedWeeklyMemory
WeeklyMemory.RememberWeeklyCompletion = rememberWeeklyCompletion
