-- Copyright (c) 2024 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 Databases = require 'database'
local Col = require 'database.column'

local SyssdmEnums = require 'syssdm.types.enums'

---@class SyscmdAgentTable: Table
---@field SysUpgradeState FieldBase

---@class SysconfAgentTable: Table
---@field CertificatePath FieldBase
---@field SysConfState FieldBase

---@class SyssdmDBDatabase
---@field db DataBase
---@field select fun(db:DataBase, table: any, ...): SelectStatement
---@field update fun(db:DataBase, table: any, ...): UpdateStatement
---@field insert fun(db:DataBase, table: any, ...): InsertStatement
---@field SyscmdAgent SyscmdAgentTable
---@field SysconfAgent SysconfAgentTable
local SyssdmDBDatabase = {}
SyssdmDBDatabase.__index = SyssdmDBDatabase

function SyssdmDBDatabase.new(path, datas)
    local db = Databases(path)
    local obj = {db = db}

    local tables = {}
    obj.SyscmdAgent = db:Table('t_syscmd_agent', {
        SysUpgradeState = Col.EnumField(SyssdmEnums.UpgradeState):cid(1):default(
            SyssdmEnums.UpgradeState.UpgradeIdle)
    }, 'protect_power_off'):create_if_not_exist(datas and datas['t_syscmd_agent'])
    tables['t_syscmd_agent'] = obj.SyscmdAgent
    obj.SysconfAgent = db:Table('t_sysconf_agent', {
        CertificatePath = Col.TextField():cid(1):max_length(256):default('etc'),
        SysConfState = Col.EnumField(SyssdmEnums.ConfigState):cid(2):default(SyssdmEnums.ConfigState
                                                                                 .ConfigIdle)
    }, 'protect_power_off'):create_if_not_exist(datas and datas['t_sysconf_agent'])
    tables['t_sysconf_agent'] = obj.SysconfAgent

    obj.tables = tables
    return setmetatable(obj, SyssdmDBDatabase)
end

function SyssdmDBDatabase:select(table, ...)
    return self.db:select(table, ...)
end

function SyssdmDBDatabase:update(table, ...)
    return self.db:update(table, ...)
end

function SyssdmDBDatabase:insert(table, ...)
    return self.db:insert(table, ...)
end

function SyssdmDBDatabase:delete(table, ...)
    return self.db:delete(table, ...)
end

return SyssdmDBDatabase.new
