-- Copyright (c) 2026 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
local lu = require 'luaunit'

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

TestSyncTask = {}

function TestSyncTask:setUp()
    self._orig_create_task = task_mgmt.create_task
    self._orig_update_task = task_mgmt.update_task
    self._orig_get_task_obj = task_mgmt.get_task_obj
    self._orig_destroy_task = task_mgmt.destroy_task
    self._orig_log_error = log.error
end

function TestSyncTask:tearDown()
    if self._orig_create_task then task_mgmt.create_task = self._orig_create_task end
    if self._orig_update_task then task_mgmt.update_task = self._orig_update_task end
    if self._orig_get_task_obj then task_mgmt.get_task_obj = self._orig_get_task_obj end
    if self._orig_destroy_task then task_mgmt.destroy_task = self._orig_destroy_task end
    if self._orig_log_error then log.error = self._orig_log_error end
end

function TestSyncTask:test_create_task_success()
    local sync_task = require 'sync_task'
    task_mgmt.create_task = function()
        return task_mgmt.create_code.TASK_CREATE_SUCCESSFUL, nil, 123
    end
    local id = sync_task.create_task({}, 'TaskName', '/path')
    lu.assertEquals(id, 123)
end

function TestSyncTask:test_create_task_failed_raises_error()
    local sync_task = require 'sync_task'
    task_mgmt.create_task = function()
        -- 直接抛错，验证 sync_task.create_task 会把底层错误透传出去
        error('create_failed')
    end
    log.error = function() end
    local ok, err = pcall(sync_task.create_task, {}, 'TaskName', '/path')
    lu.assertFalse(ok)
    lu.assertStrContains(tostring(err), 'create_failed')
end

function TestSyncTask:test_update_task_prop_logs_error_when_failed()
    local sync_task = require 'sync_task'
    local logged = false
    task_mgmt.update_task = function()
        -- 返回非成功码，触发日志分支
        return -1
    end
    log.error = function() logged = true end
    sync_task.update_task_prop(1, { State = task_mgmt.state.Running })
    lu.assertTrue(logged)
end

function TestSyncTask:test_get_task_running_states()
    local sync_task = require 'sync_task'
    task_mgmt.get_task_obj = function(task_id)
        if task_id == 1 then
            return { State = task_mgmt.state.Running }
        elseif task_id == 2 then
            return { State = task_mgmt.state.Completed }
        else
            return nil
        end
    end

    lu.assertTrue(sync_task.get_task_running(1))
    lu.assertFalse(sync_task.get_task_running(2))
    lu.assertFalse(sync_task.get_task_running(3))
end

function TestSyncTask:test_destroy_task_calls_underlying_api()
    local sync_task = require 'sync_task'
    local destroyed
    task_mgmt.destroy_task = function(task_id)
        destroyed = task_id
    end
    sync_task.destroy_task(99)
    lu.assertEquals(destroyed, 99)
end

