# frozen_string_literal: true

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

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

# 缓存脚本模型
class CachedScript < Sequel::Model(:cached_scripts)
  # Sequel模型插件
  plugin :timestamps, update_on_create: true
  plugin :validation_helpers
  plugin :json_serializer
  
  # 验证
  def validate
    super
    validates_presence :name
    validates_presence :code
  end
  
  # 转换为API哈希
  def to_api_hash
    {
      id: id,
      name: name,
      description: description,
      code: code,
      version: version,
      device_model_pattern: device_model_pattern,
      created_at: created_at&.iso8601,
      updated_at: updated_at&.iso8601,
      last_used_at: last_used_at&.iso8601
    }
  end
  
  # 从云端数据创建或更新脚本
  def self.create_or_update_from_cloud(cloud_script)
    LogService.debug("[CachedScript] create_or_update_from_cloud 被调用, 云端数据: id=#{cloud_script['id']}, name=#{cloud_script['name']}")
    
    script = CachedScript[id: cloud_script['id']] || CachedScript.new
    
    is_new = script.new?
    LogService.debug("[CachedScript] 脚本 #{cloud_script['id']} 是否为新记录: #{is_new}")
    
    script.id = cloud_script['id']
    script.name = cloud_script['name']
    script.description = cloud_script['description']
    script.code = cloud_script['code']
    script.commands = cloud_script['commands'].to_json if cloud_script['commands']
    script.version = cloud_script['version']
    script.device_model_pattern = cloud_script['device_model_pattern']


    LogService.debug("[CachedScript] 准备保存脚本: id=#{script.id}, name=#{script.name}, version=#{script.version}")

    begin
      saved_result = script.save
      LogService.debug("[CachedScript] 脚本保存#{saved_result ? '成功' : '失败'}")

      if saved_result
        LogService.debug("[CachedScript] 保存后的脚本: id=#{script.id}, created_at=#{script.created_at}, updated_at=#{script.updated_at}")
      else
        LogService.debug("[CachedScript] 保存失败，错误信息: #{script.errors.inspect}")
      end
    rescue StandardError => e
      LogService.error("[CachedScript] 保存脚本异常: #{e.message}")
      LogService.debug('[CachedScript] 异常堆栈: ' + e.backtrace.join("\n"))
      raise
    end

    script
  end
end
