--[[
    Commander 3.0 - Class Helper

    Simple OOP implementation for Lua.
    Supports inheritance, constructors, and method chaining.
]]

local ADDON_NAME, C3 = ...

---Create a new class
---@param base? table Optional base class to inherit from
---@return table class The new class
local function class(base)
    local cls = {}
    cls.__index = cls

    -- Inherit from base class
    if base then
        setmetatable(cls, {
            __index = base,
            __call = function(self, ...)
                return self:new(...)
            end,
        })
        cls._base = base
    else
        setmetatable(cls, {
            __call = function(self, ...)
                return self:new(...)
            end,
        })
    end

    ---Create a new instance
    ---@param ... any Constructor arguments
    ---@return table instance
    function cls:new(...)
        local instance = setmetatable({}, self)

        -- Call constructor if defined
        if instance.init then
            instance:init(...)
        end

        return instance
    end

    ---Create a subclass
    ---@return table subclass
    function cls:extend()
        return class(self)
    end

    ---Check if instance is of this class or a subclass
    ---@param instance table
    ---@return boolean
    function cls:isInstance(instance)
        local mt = getmetatable(instance)
        while mt do
            if mt == self then
                return true
            end
            mt = mt._base
        end
        return false
    end

    ---Call parent method
    ---@param methodName string
    ---@param ... any
    ---@return any
    function cls:super(methodName, ...)
        if self._base and self._base[methodName] then
            return self._base[methodName](self, ...)
        end
    end

    return cls
end

-- Export
C3.class = class

return class
