-- 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 base_messages = require 'messages.base'
local log = require 'mc.logging'
local json = require 'cjson'

local M = {}

local CONFIG_DATA = "ConfigData"
local dealers = {}

local function do_import_item(ctx, class_name, obj_json)
    local dealer = dealers[class_name]
    if not dealer then
        log:error("[network_adapter] import: class(%s) not registered", class_name)
        error(base_messages.InternalError())
    end
    dealer:import(ctx, obj_json)
end

local function do_import_class(ctx, class_name, object_list)
    if type(object_list) ~= 'table' or #object_list == 0 then
        return
    end
    for _, obj in pairs(object_list) do
        do_import_item(ctx, class_name, obj)
    end
end

--- 初始化：注册内置 dealer，由应用显式调用
function M.init()
    local preload_dealer = require 'config_mgmt.dealers.preload'
    M.register_dealer("NetworkAdapterPreload", preload_dealer.new())
end

local function parse_config(config_str)
    local ok, config = pcall(json.decode, config_str)
    if not ok or not config then
        log:error("[network_adapter] import: invalid json")
        error(base_messages.MalformedJSON())
    end
    return config[CONFIG_DATA]
end

--- 注册配置处理器，已有则记录错误日志不覆盖
function M.register_dealer(class_name, dealer)
    if dealers[class_name] then
        log:error("[network_adapter] config_mgmt: dealer %s already registered, skip", class_name)
        return
    end
    dealers[class_name] = dealer
end

local function throw_export_error(ctx)
    log:error("[network_adapter] export: failed")
    error(base_messages.InternalError())
end

--- 配置导出（操作日志由 OMS 统一记录，此处不记录）
function M.export(ctx, export_type)
    local config = {}
    for class_name, dealer in pairs(dealers) do
        config[class_name] = dealer:export()
    end
    local result = {[CONFIG_DATA] = config}
    local ok, encoded = pcall(json.encode, result)
    if not ok then
        log:error("[network_adapter] export: encode failed")
        throw_export_error(ctx)
    end
    return encoded
end

--- 配置导入
function M.import(ctx, config_str, import_type)
    local config = parse_config(config_str)
    if not config then
        log:notice('[network_adapter] import: no ConfigData')
        return
    end
    for class_name, data in pairs(config) do
        do_import_class(ctx, class_name, data)
    end
end

return M
