-- Copyright (c) 2024-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 util

TEST_import_export_util = {}

function TEST_import_export_util.setUp()
    package.loaded['common.common_func'] = nil
    package.loaded['mc.initiator'] = nil
    package.loaded['config_mgmt.import_export_util'] = nil

    local mock_common_func = {
        has_initiator = function(_, ctx)
            return ctx and ctx.Interface and ctx.UserName and ctx.ClientAddr
        end
    }
    package.preload['common.common_func'] = function()
        return mock_common_func
    end

    package.preload['mc.initiator'] = function()
        return {
            new = function(_, __, addr)
                return { Interface = 'N/A', UserName = 'N/A', ClientAddr = addr or 'localhost' }
            end
        }
    end

    util = require 'config_mgmt.import_export_util'
end

function TEST_import_export_util.test_get_initiator_with_valid_ctx()
    local ctx = {
        Interface = 'Redfish',
        UserName = 'admin',
        ClientAddr = '127.0.0.1',
        get_initiator = function()
            return { Interface = 'Redfish', UserName = 'admin', ClientAddr = '127.0.0.1' }
        end
    }
    local initiator = util.get_initiator(ctx)
    lu.assertEquals(initiator.UserName, 'admin')
    lu.assertEquals(initiator.Interface, 'Redfish')
end

function TEST_import_export_util.test_get_initiator_with_nil_ctx()
    local initiator = util.get_initiator(nil)
    lu.assertEquals(initiator.ClientAddr, 'localhost')
    lu.assertEquals(initiator.UserName, 'N/A')
end

function TEST_import_export_util.test_get_initiator_returns_default_when_no_valid_initiator()
    local ctx = { get_initiator = function() return {} end }
    local initiator = util.get_initiator(ctx)
    lu.assertEquals(initiator.ClientAddr, 'localhost')
end

function TEST_import_export_util.test_should_import_nil_val()
    lu.assertFalse(util.should_import(nil, 0))
end

function TEST_import_export_util.test_should_import_explicit_false()
    lu.assertFalse(util.should_import({ Value = 1, Import = false }, 0))
end

function TEST_import_export_util.test_should_import_same_value()
    lu.assertFalse(util.should_import({ Value = 5, Import = true }, 5))
end

function TEST_import_export_util.test_should_import_returns_true()
    lu.assertTrue(util.should_import({ Value = 5, Import = true }, 0))
    lu.assertTrue(util.should_import({ Value = 3 }, 1))
end
