local open_db = require 'observability.db'
local utils = require 'mc.utils'
local datas = require 'observability.datas'
local db_path = './test_observability.test.db'
local m_config = require 'public.config'
local m_control = require 'public.control'
local defs = require 'public.defs'
local unit_data_dir = utils.realpath('.')
local cert_dir = unit_data_dir .. '/cert_key'
local cert_file = cert_dir .. '/SSL.key'

TestCtrl = {}

function TestCtrl:setupClass()
    self.db = open_db(db_path, datas)
    self.config = m_config.new(self.db)
    self.control = m_control.new(self.db)
    os.execute('mkdir -p ' .. cert_dir)
    os.execute('touch ' .. defs.TLS_CA_FILE_PATH)
    os.execute('echo test > ' .. defs.TLS_CA_FILE_PATH)
    os.execute('touch ' .. cert_file)
    os.execute('echo test > ' .. cert_file)
    os.execute('mkdir -p ' .. defs.SSL_KEY_PATH)
    os.execute('touch ' .. defs.SSL_KEY_FILE_PATH)
end

function TestCtrl:teardownClass()
    utils.remove_file(db_path)
    utils.remove_file(defs.TLS_CA_FILE_PATH)
    utils.remove_file(cert_file)
    utils.remove_file(defs.SSL_KEY_FILE_PATH)
end

function TestCtrl:test_generate_mtls_config()
    self.db:update(self.db.ObservabilityService):value({TLSMode = "mTLS"}):exec()
    self.config:get_persistence_config(0)
end

function TestCtrl:test_write_fifo()
    self.db:update(self.db.ObservabilityService):value({TLSMode = "TLS"}):exec()
    self.config:write_data_to_fifo()

    self.config.key_text = ' '
    self.db:update(self.db.ObservabilityService):value({TLSMode = "mTLS"}):exec()
    os.execute('rm -f ' .. defs.SSL_KEY_FILE_PATH)
    self.config:write_data_to_fifo()
end

function TestCtrl:test_update_fluent_bit_state()
    self.db:update(self.db.ObservabilityService):value({Enabled = true}):exec()
    self.db:update(self.db.Receivers):where({ReceiverId = 0}):value({Enabled = true}):exec()
    self.control:update_fluent_bit_state()

    self.db:update(self.db.ObservabilityService):value({Enabled = false}):exec()
    self.control:update_fluent_bit_state()

    self.db:update(self.db.ObservabilityService):value({Enabled = true}):exec()
    self.control:update_fluent_bit_state()
end

function TestCtrl:test_set_state_flag()
    self.control:set_state_flag()
end