local PT = AhUI
PT.tradeSkillReady = false

AhUI_CharConfig = AhUI_CharConfig or {}
AhUI_CharConfig.activeDB = AhUI_CharConfig.activeDB or "DF"

PT.config = PT.config or {}
PT.config.activeDB = AhUI_CharConfig.activeDB

PT.DB = PT.DB or {}
PT.DB.DF  = PT.DB.DF  or {}
PT.DB.TWW = PT.DB.TWW or {}
PT.DB.MID = PT.DB.MID or {}

local function ImportDB(globalName, target)
    local g = _G[globalName]
    if g and type(g) == "table" then
        for k,v in pairs(g) do
            target[k] = v
        end
    end
end

function PT.LoadActiveDB()
    local key = AhUI_CharConfig.activeDB or "DF"

    PT.db = PT.DB[key] or {}
    PT.professions = nil

    AhUI_CharConfig.activeDB = key
    PT.config.activeDB = key

    return PT.db
end

PT.GetProfessionsByDB = {}

local function PlayerHasSkillLine(skillLineID)
    local prof1, prof2, arch, fish, cook = GetProfessions()

    for _, profIndex in ipairs({ prof1, prof2, arch, fish, cook }) do
        if profIndex then
            local _, _, _, _, _, _, skillLine = GetProfessionInfo(profIndex)
            if skillLine == skillLineID then
                return true
            end
        end
    end

    return false
end

PT.GetProfessionsByDB.DF = function(db, refresh)
    local result = {}

    for id, prof in pairs(db or {}) do
        if type(prof) == "table" then
            local skillInfo = prof:GetSkillLevel()
            if skillInfo and skillInfo.skillLevel > 0 then
                result[id] = prof
            end
        end
    end

    return result
end

PT.GetProfessionsByDB.TWW = function(db, refresh)
    local result = {}

    for id, prof in pairs(db or {}) do
        if type(prof) == "table" then
            if PT.config.showAllProfessions
               or (prof.spellId and IsPlayerSpell(prof.spellId))
            then
                result[id] = prof
            end
        end
    end

    return result
end

PT.GetProfessionsByDB.MID = function(db, refresh)
    local result = {}

    if not PT.IS_MID_AVAILABLE then
        return result
    end

    for id, prof in pairs(db or {}) do
        if type(prof) == "table" then
            if PlayerHasSkillLine(prof.skillLine or prof.id) then
				result[id] = prof
			end
		end
    end

    return result
end

function PT.GetProfessions(refresh)
    if not PT.tradeSkillReady then
        return {}
    end
    local dbKey = PT.config.activeDB or "DF"
    local db    = PT.db or {}
    local fn    = PT.GetProfessionsByDB[dbKey]

    if not fn then
        return {}
    end

    local result = fn(db, refresh)

    PT.professions = result

    for _, prof in pairs(result) do
        if prof.RefreshInfo then
            prof:RefreshInfo()
        end
    end

    return result
end
local f = CreateFrame("Frame")
f:RegisterEvent("TRADE_SKILL_LIST_UPDATE")
f:RegisterEvent("SKILL_LINES_CHANGED")

f:SetScript("OnEvent", function(_, event)
    PT.tradeSkillReady = true
    PT.UpdateAllProfessionNames()
    PT:RefreshData()
    PT:RefreshUI()
end)
