-- 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 lu = require 'luaunit'
local c_psu_object = require 'device.psu'

-- 在加载 metric_collect 之前构造简化的 PSU 集合，避免依赖底层 ORM
if not c_psu_object.collection then
    c_psu_object.collection = {}
end

local objects = {
        { path = 1, InputPowerWatts = 88, OutputPowerWatts = 66,
            EnergykWh = 123, EnergySensorResetTime = "2025-01-01T00:00:00Z", SlotNumber = 1 },
        { path = 2 }
}
c_psu_object.collection.objects = objects
c_psu_object.collection.find = function (_, cond)
    if type(cond) ~= 'function' then
        return nil
    end
    for _, obj in ipairs(objects) do
        if cond(obj) then
            return obj
        end
    end
    return nil
end

local metric_collect = require 'metric_collect'

local PSU_POWER <const> = 'psu.power'
local PSU_POWEROUT <const> = 'psu.powerout'

TestMetricCollect = {}

function TestMetricCollect:test_get_psu_data_collection_data()
    local psu1 = {path = 1}
    local ans1 = metric_collect.get_psu_data_collection_data(
        metric_collect, psu1, {PSU_POWER, PSU_POWEROUT}
    )
    lu.assertEquals(ans1[1]['Data'][1], '88')
    lu.assertEquals(ans1[2]['Data'][1], '66')

    local psu2 = {path = 2}
    local ans2 = metric_collect.get_psu_data_collection_data(
        metric_collect, psu2, {PSU_POWER, PSU_POWEROUT}
    )
    -- 对于 path = 2 的 PSU 对象，当前实现会插入两条 \"nil\" 字符串数据
    lu.assertEquals(#ans2, 2)
end

function TestMetricCollect:test_reset_psu_metrics_success()
    local psu1 = { path = 1 }
    -- ensure pre-conditions
    local psu_obj = c_psu_object.collection:find(function(o) return o.path == psu1.path end)
    lu.assertNotNil(psu_obj)
    lu.assertEquals(psu_obj.EnergykWh, 123)
    lu.assertEquals(psu_obj.EnergySensorResetTime, "2025-01-01T00:00:00Z")

    -- call reset (no ctx)
    metric_collect:reset_psu_metrics(nil, psu1)

    -- verify reset
    lu.assertEquals(psu_obj.EnergykWh, 0)
    lu.assertEquals(psu_obj.EnergySensorResetTime, "")
end
