# frozen_string_literal: true

require 'sequel'
require 'json'
require 'securerandom'
require_relative '../config/database'
require_relative '../services/password_encryptor'

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

# 本地设备模型（存储连接凭证）
class LocalDevice < Sequel::Model(:local_devices)
  # Sequel模型插件
  plugin :timestamps, update_on_create: true
  plugin :validation_helpers
  plugin :json_serializer
  
  # 连接类型枚举
  CONNECTION_TYPES = %w[telnet ssh].freeze
  
  # 验证
  def validate
    super
    validates_presence :name
    validates_unique :name
    validates_presence :ip_address
    validates_numeric :port, between: 1..65535, message: "端口必须在1-65535范围内"
    validates_includes CONNECTION_TYPES, :connection_type, message: "连接类型必须是telnet或ssh"
  end
  
  # 创建前生成UUID
  def before_create
    self.id ||= SecureRandom.uuid
    super
  end
  
  # 密码加密（可逆加密，用于设备连接）
  def password=(plain_password)
    return if plain_password.nil? || plain_password.empty?
    
    self.encrypted_password = password_encryptor.encrypt(plain_password)
  end
  
  # 特权模式密码加密
  def enable_password=(plain_password)
    return if plain_password.nil? || plain_password.empty?

    self.encrypted_enable_password = password_encryptor.encrypt(plain_password)
  end

  # Root密码加密
  def root_password=(plain_password)
    return if plain_password.nil? || plain_password.empty?

    self.encrypted_root_password = password_encryptor.encrypt(plain_password)
  end
  
  # 解密密码
  def decrypt_password
    return nil if encrypted_password.nil? || encrypted_password.empty?
    
    # 检查是否是有效的加密格式
    return nil unless password_encryptor.aes_encrypted?(encrypted_password)
    
    begin
      password_encryptor.decrypt(encrypted_password)
    rescue PasswordEncryptor::DecryptionError => e
      # 只在调试模式记录详细错误
      LogService.debug("密码解密失败: #{e.message}")
      nil
    end
  end
  
  # 解密特权模式密码
  def decrypt_enable_password
    return nil if encrypted_enable_password.nil? || encrypted_enable_password.empty?

    # 检查是否是有效的加密格式
    return nil unless password_encryptor.aes_encrypted?(encrypted_enable_password)

    begin
      password_encryptor.decrypt(encrypted_enable_password)
    rescue PasswordEncryptor::DecryptionError => e
      # 只在调试模式记录详细错误
      LogService.debug("特权密码解密失败: #{e.message}")
      nil
    end
  end

  # 解密Root密码
  def decrypt_root_password
    return nil if encrypted_root_password.nil? || encrypted_root_password.empty?

    # 检查是否是有效的加密格式
    return nil unless password_encryptor.aes_encrypted?(encrypted_root_password)

    begin
      password_encryptor.decrypt(encrypted_root_password)
    rescue PasswordEncryptor::DecryptionError => e
      # 只在调试模式记录详细错误
      LogService.debug("Root密码解密失败: #{e.message}")
      nil
    end
  end
  
  # 完整连接信息（用于脚本执行）
  def full_connection_info
    {
      host: ip_address,
      port: port,
      username: username,
      password: encrypted_password ? '***' : nil,
      ssh_key_path: ssh_key_path
    }
  end
  
  # 云端同步信息（不包含敏感信息）
  def cloud_sync_info
    {
      id: id,  # 直接使用客户端的 UUID 作为服务端的主键
      name: name,
      device_model: device_model,
      description: description,
      active: active
    }
  end
  
  
  
  # 类方法
  
  # 按设备型号搜索
  def self.find_by_model(model_pattern)
    return [] if model_pattern.nil? || model_pattern.empty?
    
    dataset.where(Sequel.like(:device_model, "%#{model_pattern}%")).all
  end
  
  # 活跃设备
  def self.active
    dataset.where(active: true).all
  end
  
  
  
  private
  
  def password_encryptor
    @password_encryptor ||= PasswordEncryptor.new
  end
end