'use strict';

var drizzleOrm = require('drizzle-orm');
var pgCore = require('drizzle-orm/pg-core');

// src/testYourself/server/ConfigService.ts
var LocalStorageAdapter = class {
  constructor() {
    this.STORAGE_KEY = "test-yourself-configs";
    this.DEFAULT_KEY = "test-yourself-default-config";
  }
  async getAllConfigsData() {
    if (typeof window === "undefined") return [];
    try {
      const data = localStorage.getItem(this.STORAGE_KEY);
      return data ? JSON.parse(data) : [];
    } catch (error) {
      console.error("\u8BFB\u53D6\u914D\u7F6E\u5931\u8D25:", error);
      return [];
    }
  }
  async saveAllConfigsData(configs) {
    if (typeof window === "undefined") return;
    try {
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify(configs));
    } catch (error) {
      console.error("\u4FDD\u5B58\u914D\u7F6E\u5931\u8D25:", error);
      throw error;
    }
  }
  async saveConfig(config) {
    const configs = await this.getAllConfigsData();
    const existingIndex = configs.findIndex((c) => c.id === config.id);
    if (existingIndex >= 0) {
      configs[existingIndex] = config;
    } else {
      configs.push(config);
    }
    await this.saveAllConfigsData(configs);
  }
  async getConfig(id) {
    const configs = await this.getAllConfigsData();
    return configs.find((c) => c.id === id) || null;
  }
  async getAllConfigs() {
    return this.getAllConfigsData();
  }
  async deleteConfig(id) {
    const configs = await this.getAllConfigsData();
    const filtered = configs.filter((c) => c.id !== id);
    await this.saveAllConfigsData(filtered);
  }
  async updateConfig(id, config) {
    const configs = await this.getAllConfigsData();
    const index2 = configs.findIndex((c) => c.id === id);
    if (index2 >= 0) {
      configs[index2] = { ...config, updatedAt: Date.now() };
      await this.saveAllConfigsData(configs);
    } else {
      throw new Error("\u914D\u7F6E\u4E0D\u5B58\u5728: " + id);
    }
  }
  async setDefaultConfig(id) {
    if (typeof window === "undefined") return;
    const config = await this.getConfig(id);
    if (!config) {
      throw new Error("\u914D\u7F6E\u4E0D\u5B58\u5728: " + id);
    }
    const configs = await this.getAllConfigsData();
    configs.forEach((c) => c.isDefault = c.id === id);
    await this.saveAllConfigsData(configs);
    localStorage.setItem(this.DEFAULT_KEY, id);
  }
  async getDefaultConfig() {
    if (typeof window === "undefined") return null;
    try {
      const defaultId = localStorage.getItem(this.DEFAULT_KEY);
      if (defaultId) {
        return await this.getConfig(defaultId);
      }
      const configs = await this.getAllConfigsData();
      return configs.find((c) => c.isDefault) || null;
    } catch (error) {
      console.error("\u83B7\u53D6\u9ED8\u8BA4\u914D\u7F6E\u5931\u8D25:", error);
      return null;
    }
  }
};
var MemoryStorageAdapter = class {
  constructor() {
    this.configs = /* @__PURE__ */ new Map();
    this.defaultConfigId = null;
  }
  async saveConfig(config) {
    this.configs.set(config.id, config);
  }
  async getConfig(id) {
    return this.configs.get(id) || null;
  }
  async getAllConfigs() {
    return Array.from(this.configs.values());
  }
  async deleteConfig(id) {
    this.configs.delete(id);
    if (this.defaultConfigId === id) {
      this.defaultConfigId = null;
    }
  }
  async updateConfig(id, config) {
    if (!this.configs.has(id)) {
      throw new Error("\u914D\u7F6E\u4E0D\u5B58\u5728: " + id);
    }
    this.configs.set(id, { ...config, updatedAt: Date.now() });
  }
  async setDefaultConfig(id) {
    if (!this.configs.has(id)) {
      throw new Error("\u914D\u7F6E\u4E0D\u5B58\u5728: " + id);
    }
    this.configs.forEach((c) => c.isDefault = c.id === id);
    this.defaultConfigId = id;
  }
  async getDefaultConfig() {
    if (this.defaultConfigId) {
      return this.configs.get(this.defaultConfigId) || null;
    }
    for (const config of this.configs.values()) {
      if (config.isDefault) {
        return config;
      }
    }
    return null;
  }
};
var ConfigService = class {
  constructor(options = {}) {
    this.cache = /* @__PURE__ */ new Map();
    const {
      storageType = "localStorage",
      customStorage,
      enableCache = true
    } = options;
    this.enableCache = enableCache;
    if (customStorage) {
      this.storage = customStorage;
    } else if (storageType === "memory") {
      this.storage = new MemoryStorageAdapter();
    } else {
      this.storage = new LocalStorageAdapter();
    }
  }
  /**
   * 初始化服务（如果需要）
   */
  async init() {
  }
  /**
   * 生成唯一ID
   */
  generateId() {
    return "config_" + Date.now() + "_" + Math.random().toString(36).substring(2, 9);
  }
  /**
   * 保存配置
   */
  async saveConfig(config) {
    await this.storage.saveConfig(config);
    if (config.isDefault) {
      await this.storage.setDefaultConfig(config.id);
    }
    if (this.enableCache) {
      this.cache.set(config.id, config);
    }
  }
  /**
   * 创建新配置
   */
  async createConfig(name, config, description, isDefault = false) {
    const savedConfig = {
      id: this.generateId(),
      name,
      description,
      config,
      createdAt: Date.now(),
      updatedAt: Date.now(),
      isDefault
    };
    await this.storage.saveConfig(savedConfig);
    if (isDefault) {
      await this.storage.setDefaultConfig(savedConfig.id);
    }
    if (this.enableCache) {
      this.cache.set(savedConfig.id, savedConfig);
    }
    return savedConfig;
  }
  /**
   * 获取配置
   */
  async getConfig(id) {
    if (this.enableCache && this.cache.has(id)) {
      return this.cache.get(id);
    }
    const config = await this.storage.getConfig(id);
    if (config && this.enableCache) {
      this.cache.set(id, config);
    }
    return config;
  }
  /**
   * 获取所有配置列表
   */
  async getAllConfigs() {
    return await this.storage.getAllConfigs();
  }
  /**
   * 获取配置列表（精简版）
   */
  async getConfigList() {
    const configs = await this.getAllConfigs();
    return configs.map((c) => ({
      id: c.id,
      name: c.name,
      description: c.description,
      resultCount: c.config.results.length,
      createdAt: c.createdAt,
      updatedAt: c.updatedAt,
      isDefault: c.isDefault
    }));
  }
  /**
   * 更新配置
   */
  async updateConfig(id, updates) {
    const existing = await this.getConfig(id);
    if (!existing) {
      throw new Error("\u914D\u7F6E\u4E0D\u5B58\u5728: " + id);
    }
    const updated = {
      ...existing,
      ...updates,
      updatedAt: Date.now()
    };
    await this.storage.updateConfig(id, updated);
    if (updates.isDefault) {
      await this.storage.setDefaultConfig(id);
    }
    if (this.enableCache) {
      this.cache.set(id, updated);
    }
    return updated;
  }
  /**
   * 删除配置
   */
  async deleteConfig(id) {
    await this.storage.deleteConfig(id);
    if (this.enableCache) {
      this.cache.delete(id);
    }
  }
  /**
   * 设置默认配置
   */
  async setDefaultConfig(id) {
    await this.storage.setDefaultConfig(id);
    if (this.enableCache) {
      this.cache.clear();
    }
  }
  /**
   * 获取默认配置
   */
  async getDefaultConfig() {
    return await this.storage.getDefaultConfig();
  }
  /**
   * 清空缓存
   */
  clearCache() {
    this.cache.clear();
  }
  /**
   * 导出配置（JSON格式）
   */
  async exportConfig(id) {
    const config = await this.getConfig(id);
    if (!config) {
      throw new Error("\u914D\u7F6E\u4E0D\u5B58\u5728: " + id);
    }
    return JSON.stringify(config, null, 2);
  }
  /**
   * 导入配置
   */
  async importConfig(jsonString) {
    try {
      const data = JSON.parse(jsonString);
      const newConfig = {
        ...data,
        id: this.generateId(),
        createdAt: Date.now(),
        updatedAt: Date.now(),
        isDefault: false
        // 导入的配置不设为默认
      };
      await this.storage.saveConfig(newConfig);
      if (this.enableCache) {
        this.cache.set(newConfig.id, newConfig);
      }
      return newConfig;
    } catch (error) {
      throw new Error("\u5BFC\u5165\u914D\u7F6E\u5931\u8D25: " + error);
    }
  }
  /**
   * 复制配置
   */
  async duplicateConfig(id, newName) {
    const original = await this.getConfig(id);
    if (!original) {
      throw new Error("\u914D\u7F6E\u4E0D\u5B58\u5728: " + id);
    }
    const duplicated = {
      ...original,
      id: this.generateId(),
      name: newName || original.name + " (\u526F\u672C)",
      createdAt: Date.now(),
      updatedAt: Date.now(),
      isDefault: false
    };
    await this.storage.saveConfig(duplicated);
    if (this.enableCache) {
      this.cache.set(duplicated.id, duplicated);
    }
    return duplicated;
  }
  /**
   * 批量删除配置
   */
  async deleteConfigs(ids) {
    for (const id of ids) {
      await this.deleteConfig(id);
    }
  }
};
function createConfigService(options) {
  return new ConfigService(options);
}
var defaultServiceInstance = null;
function getDefaultConfigService() {
  if (!defaultServiceInstance) {
    defaultServiceInstance = createConfigService();
  }
  return defaultServiceInstance;
}
var testYourselfConfigs = pgCore.pgTable(
  "test_yourself_configs",
  {
    // ========== 主键 ==========
    /** 配置唯一ID */
    id: pgCore.uuid("id").primaryKey().defaultRandom(),
    // ========== 基本信息 ==========
    /** 配置名称 */
    name: pgCore.varchar("name", { length: 255 }).notNull(),
    /** 配置描述 */
    description: pgCore.text("description"),
    /** 配置标签（用于分类和搜索） */
    tags: pgCore.json("tags").$type().default([]),
    // ========== 配置数据 ==========
    /** 测试配置内容（JSON格式） */
    config: pgCore.json("config").$type().notNull(),
    /** 结果数量（冗余字段，便于查询） */
    resultCount: pgCore.integer("result_count").notNull().default(0),
    // ========== 状态字段 ==========
    /** 是否为默认配置 */
    isDefault: pgCore.boolean("is_default").notNull().default(false),
    /** 是否已发布（草稿/发布） */
    isPublished: pgCore.boolean("is_published").notNull().default(true),
    /** 是否已归档 */
    isArchived: pgCore.boolean("is_archived").notNull().default(false),
    /** 是否已删除（软删除） */
    isDeleted: pgCore.boolean("is_deleted").notNull().default(false),
    // ========== 权限和所有权 ==========
    /** 创建者ID */
    createdBy: pgCore.varchar("created_by", { length: 255 }).notNull(),
    /** 最后更新者ID */
    updatedBy: pgCore.varchar("updated_by", { length: 255 }),
    /** 所属组织/租户ID（多租户支持） */
    organizationId: pgCore.varchar("organization_id", { length: 255 }),
    // ========== 统计信息 ==========
    /** 使用次数 */
    usageCount: pgCore.integer("usage_count").notNull().default(0),
    /** 最后使用时间 */
    lastUsedAt: pgCore.timestamp("last_used_at"),
    /** 浏览次数 */
    viewCount: pgCore.integer("view_count").notNull().default(0),
    // ========== 版本控制 ==========
    /** 配置版本号 */
    version: pgCore.integer("version").notNull().default(1),
    /** 父配置ID（用于版本追踪） */
    parentId: pgCore.uuid("parent_id"),
    // ========== 自定义字段 ==========
    /** 自定义元数据（扩展字段） */
    metadata: pgCore.json("metadata").$type(),
    /** 配置来源（web/api/import） */
    source: pgCore.varchar("source", { length: 50 }),
    // ========== 时间戳 ==========
    /** 创建时间 */
    createdAt: pgCore.timestamp("created_at").defaultNow().notNull(),
    /** 更新时间 */
    updatedAt: pgCore.timestamp("updated_at").defaultNow().notNull(),
    /** 发布时间 */
    publishedAt: pgCore.timestamp("published_at"),
    /** 归档时间 */
    archivedAt: pgCore.timestamp("archived_at"),
    /** 删除时间 */
    deletedAt: pgCore.timestamp("deleted_at")
  },
  (table) => ({
    // ========== 索引设计 ==========
    /** 名称搜索索引 */
    nameIndex: pgCore.index("test_configs_name_idx").on(table.name),
    /** 创建者索引 */
    createdByIndex: pgCore.index("test_configs_created_by_idx").on(table.createdBy),
    /** 组织索引（多租户） */
    organizationIndex: pgCore.index("test_configs_organization_idx").on(table.organizationId),
    /** 默认配置索引 */
    isDefaultIndex: pgCore.index("test_configs_is_default_idx").on(table.isDefault),
    /** 发布状态索引 */
    isPublishedIndex: pgCore.index("test_configs_is_published_idx").on(table.isPublished),
    /** 删除状态索引 */
    isDeletedIndex: pgCore.index("test_configs_is_deleted_idx").on(table.isDeleted),
    /** 创建时间索引 */
    createdAtIndex: pgCore.index("test_configs_created_at_idx").on(table.createdAt),
    /** 最后使用时间索引 */
    lastUsedAtIndex: pgCore.index("test_configs_last_used_at_idx").on(table.lastUsedAt),
    /** 组合索引：组织+删除状态+发布状态 */
    orgDeletedPublishedIndex: pgCore.index("test_configs_org_deleted_published_idx").on(
      table.organizationId,
      table.isDeleted,
      table.isPublished
    ),
    /** 组合索引：创建者+删除状态 */
    createdByDeletedIndex: pgCore.index("test_configs_created_by_deleted_idx").on(
      table.createdBy,
      table.isDeleted
    )
  })
);
var testYourselfConfigUsage = pgCore.pgTable(
  "test_yourself_config_usage",
  {
    /** 记录ID */
    id: pgCore.uuid("id").primaryKey().defaultRandom(),
    /** 配置ID */
    configId: pgCore.uuid("config_id").references(() => testYourselfConfigs.id, { onDelete: "cascade" }).notNull(),
    /** 用户ID */
    userId: pgCore.varchar("user_id", { length: 255 }),
    /** 设备指纹 */
    fingerprint: pgCore.text("fingerprint"),
    /** 测试结果ID */
    resultId: pgCore.varchar("result_id", { length: 255 }),
    /** IP地址 */
    ipAddress: pgCore.varchar("ip_address", { length: 45 }),
    /** User Agent */
    userAgent: pgCore.text("user_agent"),
    /** 来源页面 */
    referer: pgCore.text("referer"),
    /** 使用时间 */
    usedAt: pgCore.timestamp("used_at").defaultNow().notNull(),
    /** 完成时间（毫秒） */
    completionTime: pgCore.integer("completion_time"),
    /** 额外数据 */
    metadata: pgCore.json("metadata").$type()
  },
  (table) => ({
    /** 配置ID索引 */
    configIndex: pgCore.index("test_usage_config_idx").on(table.configId),
    /** 用户ID索引 */
    userIndex: pgCore.index("test_usage_user_idx").on(table.userId),
    /** 使用时间索引 */
    usedAtIndex: pgCore.index("test_usage_used_at_idx").on(table.usedAt),
    /** 指纹索引 */
    fingerprintIndex: pgCore.index("test_usage_fingerprint_idx").on(table.fingerprint)
  })
);
var testYourselfConfigShares = pgCore.pgTable(
  "test_yourself_config_shares",
  {
    /** 分享ID */
    id: pgCore.uuid("id").primaryKey().defaultRandom(),
    /** 分享代码（短链接标识） */
    shareCode: pgCore.varchar("share_code", { length: 20 }).notNull().unique(),
    /** 配置ID */
    configId: pgCore.uuid("config_id").references(() => testYourselfConfigs.id, { onDelete: "cascade" }).notNull(),
    /** 分享标题 */
    title: pgCore.varchar("title", { length: 255 }),
    /** 分享描述 */
    description: pgCore.text("description"),
    /** 访问密码 */
    password: pgCore.varchar("password", { length: 100 }),
    /** 最大访问次数 */
    maxAccess: pgCore.integer("max_access"),
    /** 当前访问次数 */
    accessCount: pgCore.integer("access_count").notNull().default(0),
    /** 是否启用 */
    isActive: pgCore.boolean("is_active").notNull().default(true),
    /** 过期时间 */
    expiresAt: pgCore.timestamp("expires_at"),
    /** 创建者ID */
    createdBy: pgCore.varchar("created_by", { length: 255 }).notNull(),
    /** 创建时间 */
    createdAt: pgCore.timestamp("created_at").defaultNow().notNull(),
    /** 更新时间 */
    updatedAt: pgCore.timestamp("updated_at").defaultNow().notNull()
  },
  (table) => ({
    /** 分享代码索引 */
    shareCodeIndex: pgCore.index("test_shares_share_code_idx").on(table.shareCode),
    /** 配置ID索引 */
    configIndex: pgCore.index("test_shares_config_idx").on(table.configId),
    /** 创建者索引 */
    createdByIndex: pgCore.index("test_shares_created_by_idx").on(table.createdBy),
    /** 活跃状态索引 */
    isActiveIndex: pgCore.index("test_shares_is_active_idx").on(table.isActive)
  })
);

// src/testYourself/server/DatabaseConfigAdapter.ts
var DatabaseConfigAdapter = class {
  constructor(options) {
    this.db = options.db;
    this.userId = options.userId || "system";
    this.organizationId = options.organizationId;
    this.softDelete = options.softDelete !== false;
  }
  /**
   * 设置当前用户ID
   */
  setUserId(userId) {
    this.userId = userId;
  }
  /**
   * 设置组织ID
   */
  setOrganizationId(organizationId) {
    this.organizationId = organizationId;
  }
  /**
   * 将数据库记录转换为 SavedConfig
   */
  toSavedConfig(dbConfig) {
    return {
      id: dbConfig.id,
      name: dbConfig.name,
      description: dbConfig.description || void 0,
      config: dbConfig.config,
      createdAt: dbConfig.createdAt.getTime(),
      updatedAt: dbConfig.updatedAt.getTime(),
      isDefault: dbConfig.isDefault
    };
  }
  /**
   * 保存配置
   */
  async saveConfig(config) {
    try {
      const existing = await this.db.select().from(testYourselfConfigs).where(drizzleOrm.eq(testYourselfConfigs.id, config.id)).limit(1);
      const resultCount = config.config.results?.length || 0;
      if (existing && existing.length > 0) {
        await this.db.update(testYourselfConfigs).set({
          name: config.name,
          description: config.description || null,
          config: config.config,
          resultCount,
          isDefault: config.isDefault || false,
          updatedBy: this.userId,
          updatedAt: /* @__PURE__ */ new Date(),
          version: drizzleOrm.sql`${testYourselfConfigs.version} + 1`
          // 版本号递增
        }).where(drizzleOrm.eq(testYourselfConfigs.id, config.id));
        console.log("\u2705 [DatabaseAdapter] \u914D\u7F6E\u5DF2\u66F4\u65B0:", config.id);
      } else {
        await this.db.insert(testYourselfConfigs).values({
          id: config.id,
          name: config.name,
          description: config.description || null,
          config: config.config,
          resultCount,
          isDefault: config.isDefault || false,
          createdBy: this.userId,
          organizationId: this.organizationId,
          createdAt: new Date(config.createdAt),
          updatedAt: new Date(config.updatedAt)
        });
        console.log("\u2705 [DatabaseAdapter] \u914D\u7F6E\u5DF2\u521B\u5EFA:", config.id);
      }
    } catch (error) {
      console.error("\u274C [DatabaseAdapter] \u4FDD\u5B58\u914D\u7F6E\u5931\u8D25:", error);
      throw error;
    }
  }
  /**
   * 获取配置
   */
  async getConfig(id) {
    try {
      const conditions = [drizzleOrm.eq(testYourselfConfigs.id, id)];
      if (this.softDelete) {
        conditions.push(drizzleOrm.eq(testYourselfConfigs.isDeleted, false));
      }
      const result = await this.db.select().from(testYourselfConfigs).where(drizzleOrm.and(...conditions)).limit(1);
      if (!result || result.length === 0) {
        return null;
      }
      return this.toSavedConfig(result[0]);
    } catch (error) {
      console.error("\u274C [DatabaseAdapter] \u83B7\u53D6\u914D\u7F6E\u5931\u8D25:", error);
      throw error;
    }
  }
  /**
   * 获取所有配置列表
   */
  async getAllConfigs() {
    try {
      const conditions = [];
      if (this.softDelete) {
        conditions.push(drizzleOrm.eq(testYourselfConfigs.isDeleted, false));
      }
      if (this.organizationId) {
        conditions.push(
          drizzleOrm.or(
            drizzleOrm.eq(testYourselfConfigs.organizationId, this.organizationId),
            drizzleOrm.sql`${testYourselfConfigs.organizationId} IS NULL`
            // 包含全局配置
          )
        );
      }
      const result = await this.db.select().from(testYourselfConfigs).where(conditions.length > 0 ? drizzleOrm.and(...conditions) : void 0).orderBy(drizzleOrm.desc(testYourselfConfigs.createdAt));
      return result.map((config) => this.toSavedConfig(config));
    } catch (error) {
      console.error("\u274C [DatabaseAdapter] \u83B7\u53D6\u914D\u7F6E\u5217\u8868\u5931\u8D25:", error);
      throw error;
    }
  }
  /**
   * 删除配置
   */
  async deleteConfig(id) {
    try {
      if (this.softDelete) {
        await this.db.update(testYourselfConfigs).set({
          isDeleted: true,
          deletedAt: /* @__PURE__ */ new Date(),
          updatedBy: this.userId,
          updatedAt: /* @__PURE__ */ new Date()
        }).where(drizzleOrm.eq(testYourselfConfigs.id, id));
        console.log("\u{1F5D1}\uFE0F [DatabaseAdapter] \u914D\u7F6E\u5DF2\u8F6F\u5220\u9664:", id);
      } else {
        await this.db.delete(testYourselfConfigs).where(drizzleOrm.eq(testYourselfConfigs.id, id));
        console.log("\u{1F5D1}\uFE0F [DatabaseAdapter] \u914D\u7F6E\u5DF2\u786C\u5220\u9664:", id);
      }
    } catch (error) {
      console.error("\u274C [DatabaseAdapter] \u5220\u9664\u914D\u7F6E\u5931\u8D25:", error);
      throw error;
    }
  }
  /**
   * 更新配置
   */
  async updateConfig(id, config) {
    try {
      const resultCount = config.config.results?.length || 0;
      await this.db.update(testYourselfConfigs).set({
        name: config.name,
        description: config.description || null,
        config: config.config,
        resultCount,
        isDefault: config.isDefault || false,
        updatedBy: this.userId,
        updatedAt: new Date(config.updatedAt),
        version: drizzleOrm.sql`${testYourselfConfigs.version} + 1`
      }).where(drizzleOrm.eq(testYourselfConfigs.id, id));
      console.log("\u2705 [DatabaseAdapter] \u914D\u7F6E\u5DF2\u66F4\u65B0:", id);
    } catch (error) {
      console.error("\u274C [DatabaseAdapter] \u66F4\u65B0\u914D\u7F6E\u5931\u8D25:", error);
      throw error;
    }
  }
  /**
   * 设置默认配置
   */
  async setDefaultConfig(id) {
    try {
      await this.db.transaction(async (tx) => {
        const conditions = [drizzleOrm.eq(testYourselfConfigs.isDefault, true)];
        if (this.organizationId) {
          conditions.push(
            drizzleOrm.eq(testYourselfConfigs.organizationId, this.organizationId)
          );
        }
        await tx.update(testYourselfConfigs).set({
          isDefault: false,
          updatedBy: this.userId,
          updatedAt: /* @__PURE__ */ new Date()
        }).where(drizzleOrm.and(...conditions));
        await tx.update(testYourselfConfigs).set({
          isDefault: true,
          updatedBy: this.userId,
          updatedAt: /* @__PURE__ */ new Date()
        }).where(drizzleOrm.eq(testYourselfConfigs.id, id));
      });
      console.log("\u2705 [DatabaseAdapter] \u9ED8\u8BA4\u914D\u7F6E\u5DF2\u8BBE\u7F6E:", id);
    } catch (error) {
      console.error("\u274C [DatabaseAdapter] \u8BBE\u7F6E\u9ED8\u8BA4\u914D\u7F6E\u5931\u8D25:", error);
      throw error;
    }
  }
  /**
   * 获取默认配置
   */
  async getDefaultConfig() {
    try {
      const conditions = [drizzleOrm.eq(testYourselfConfigs.isDefault, true)];
      if (this.softDelete) {
        conditions.push(drizzleOrm.eq(testYourselfConfigs.isDeleted, false));
      }
      if (this.organizationId) {
        conditions.push(
          drizzleOrm.eq(testYourselfConfigs.organizationId, this.organizationId)
        );
      }
      const result = await this.db.select().from(testYourselfConfigs).where(drizzleOrm.and(...conditions)).limit(1);
      if (!result || result.length === 0) {
        return null;
      }
      return this.toSavedConfig(result[0]);
    } catch (error) {
      console.error("\u274C [DatabaseAdapter] \u83B7\u53D6\u9ED8\u8BA4\u914D\u7F6E\u5931\u8D25:", error);
      throw error;
    }
  }
  /**
   * 恢复已删除的配置（软删除时可用）
   */
  async restoreConfig(id) {
    if (!this.softDelete) {
      throw new Error("\u6062\u590D\u529F\u80FD\u4EC5\u5728\u542F\u7528\u8F6F\u5220\u9664\u65F6\u53EF\u7528");
    }
    try {
      await this.db.update(testYourselfConfigs).set({
        isDeleted: false,
        deletedAt: null,
        updatedBy: this.userId,
        updatedAt: /* @__PURE__ */ new Date()
      }).where(drizzleOrm.eq(testYourselfConfigs.id, id));
      console.log("\u267B\uFE0F [DatabaseAdapter] \u914D\u7F6E\u5DF2\u6062\u590D:", id);
    } catch (error) {
      console.error("\u274C [DatabaseAdapter] \u6062\u590D\u914D\u7F6E\u5931\u8D25:", error);
      throw error;
    }
  }
  /**
   * 归档配置
   */
  async archiveConfig(id) {
    try {
      await this.db.update(testYourselfConfigs).set({
        isArchived: true,
        archivedAt: /* @__PURE__ */ new Date(),
        updatedBy: this.userId,
        updatedAt: /* @__PURE__ */ new Date()
      }).where(drizzleOrm.eq(testYourselfConfigs.id, id));
      console.log("\u{1F4E6} [DatabaseAdapter] \u914D\u7F6E\u5DF2\u5F52\u6863:", id);
    } catch (error) {
      console.error("\u274C [DatabaseAdapter] \u5F52\u6863\u914D\u7F6E\u5931\u8D25:", error);
      throw error;
    }
  }
  /**
   * 取消归档
   */
  async unarchiveConfig(id) {
    try {
      await this.db.update(testYourselfConfigs).set({
        isArchived: false,
        archivedAt: null,
        updatedBy: this.userId,
        updatedAt: /* @__PURE__ */ new Date()
      }).where(drizzleOrm.eq(testYourselfConfigs.id, id));
      console.log("\u{1F4C2} [DatabaseAdapter] \u914D\u7F6E\u5DF2\u53D6\u6D88\u5F52\u6863:", id);
    } catch (error) {
      console.error("\u274C [DatabaseAdapter] \u53D6\u6D88\u5F52\u6863\u5931\u8D25:", error);
      throw error;
    }
  }
  /**
   * 记录使用次数
   */
  async incrementUsageCount(id) {
    try {
      await this.db.update(testYourselfConfigs).set({
        usageCount: drizzleOrm.sql`${testYourselfConfigs.usageCount} + 1`,
        lastUsedAt: /* @__PURE__ */ new Date()
      }).where(drizzleOrm.eq(testYourselfConfigs.id, id));
    } catch (error) {
      console.error("\u274C [DatabaseAdapter] \u66F4\u65B0\u4F7F\u7528\u6B21\u6570\u5931\u8D25:", error);
    }
  }
};
function createDatabaseConfigAdapter(options) {
  return new DatabaseConfigAdapter(options);
}

exports.ConfigService = ConfigService;
exports.DatabaseConfigAdapter = DatabaseConfigAdapter;
exports.createConfigService = createConfigService;
exports.createDatabaseConfigAdapter = createDatabaseConfigAdapter;
exports.getDefaultConfigService = getDefaultConfigService;
exports.testYourselfConfigShares = testYourselfConfigShares;
exports.testYourselfConfigUsage = testYourselfConfigUsage;
exports.testYourselfConfigs = testYourselfConfigs;
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map