# frozen_string_literal: true

require 'sequel'
require_relative '../config/database'

# 确保数据库连接已建立并设置全局Sequel模型数据库
Database.connection

# 系统设置模型
class SystemSetting < Sequel::Model(:system_settings)
  # Sequel模型插件
  plugin :timestamps, update_on_create: true
  plugin :validation_helpers
  
  # 验证
  def validate
    super
    validates_presence :key
    validates_unique :key
  end
  
  # 根据key查找或创建设置
  def self.find_or_create(key:)
    setting = SystemSetting[key: key]
    return setting if setting
    
    SystemSetting.create(key: key)
  end
  
  # 获取设置值
  def self.get(key, default: nil)
    setting = SystemSetting[key: key]
    setting ? setting.value : default
  end
  
  # 设置设置值
  def self.set(key, value)
    setting = find_or_create(key: key)
    setting.update(value: value)
    setting
  end
end
