-- Copyright (c) 2025 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
--
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local log = require 'mc.logging'
local mdb_service = require 'mc.mdb.mdb_service'

local OBJ_FDMDOMAIN_INTERFACE <const> = 'bmc.kepler.Systems.ExceptionInfo'
local m = {}
function m.get_system_fdmdomain(system_id, local_system_id)
    local base_path = string.format('/bmc/kepler/Systems/%s/FDMDomain', system_id)
    local ok, rsp = pcall(mdb_service.get_sub_paths, bus, base_path, 1, {OBJ_FDMDOMAIN_INTERFACE})
    if not ok then
        log:error('Invalid path, err(%s)', rsp)
        return ''
    end
    for _, v in pairs(rsp.SubPaths) do
        local obj = mdb.get_object(bus, v, OBJ_FDMDOMAIN_INTERFACE)
        if obj.LocalSystemId == tonumber(local_system_id) then
            log:debug('get sub FDMDomain path = %s', v)
            return v
        end
    end
    log:error('Not find sub FDMDomain, System = %s, LocalSystemId = %s', system_id, local_system_id)
    return ''
end

function m.check_fdmdomain_exist(system_id)
    local base_path = string.format('/bmc/kepler/Systems/%s/FDMDomain', system_id)
    return pcall(mdb_service.get_sub_paths, bus, base_path, 1, {OBJ_FDMDOMAIN_INTERFACE})
end

function m.service_available(system_id)
    -- Board ras导出时，system_id缺省输入为255，此时默认为system_id = 1的path
    if system_id == 255 then
        system_id = 1
    end
    local base_path = string.format('/bmc/kepler/Systems/%s/FDMDomain', system_id)
    local ok, obj =  pcall(mdb_service.get_sub_paths, bus, base_path, 1, {OBJ_FDMDOMAIN_INTERFACE})
    if not ok or not obj then
        log:debug('get FDMDomain object fail err(%s)', obj)
        error(custom_messages.ResourceNotFound('FDMDomain', "FDMDomain" .. system_id))
    end
    if #obj.SubPaths == 0 then
        log:debug('FDMDomain do not exist')
        error(custom_messages.ResourceNotFound('FDMDomain', "FDMDomain" .. system_id))
    end
    return true
end

return m