GuildHelper = GuildHelper or {}

local addon = GuildHelper

addon.Repositories = addon.Repositories or {}

local function shallowCopy(record)
    local copy = {}

    for key, value in pairs(record) do
        copy[key] = value
    end

    return copy
end

function addon.Repositories:GetTable(tableName)
    return addon.Store:GetGuild()[tableName]
end

function addon.Repositories:List(tableName, predicate)
    local records = {}
    local source = self:GetTable(tableName)

    for _, record in pairs(source) do
        if not predicate or predicate(record) then
            table.insert(records, shallowCopy(record))
        end
    end

    table.sort(records, function(left, right)
        return (left.updatedAt or 0) > (right.updatedAt or 0)
    end)

    return records
end

function addon.Repositories:Get(tableName, id)
    return self:GetTable(tableName)[id]
end

function addon.Repositories:Upsert(tableName, id, record)
    self:GetTable(tableName)[id] = record
    return record
end

function addon.Repositories:SoftDelete(tableName, id, updatedBy)
    local record = self:Get(tableName, id)

    if not record then
        return nil
    end

    record.deleted = true
    record.updatedAt = time()
    record.updatedBy = updatedBy or addon.Store:GetPlayerName()
    record.revision = (record.revision or 0) + 1

    return record
end

function addon.Repositories:NextId(prefix)
    return string.format("%s-%d-%04d", prefix, time(), math.random(0, 9999))
end
