import '../../chunk-BJTO5JO5.mjs';
import { pgTable, timestamp, text, jsonb, uniqueIndex, boolean, integer, index } from 'drizzle-orm/pg-core';
import { sql, eq } from 'drizzle-orm';
import * as crypto from 'crypto';
import crypto__default from 'crypto';

// src/config/server/types.ts
var ConfigCategory = /* @__PURE__ */ ((ConfigCategory2) => {
  ConfigCategory2["DATABASE"] = "database";
  ConfigCategory2["STORAGE"] = "storage";
  ConfigCategory2["AI_SERVICE"] = "ai_service";
  ConfigCategory2["EMAIL"] = "email";
  ConfigCategory2["SECURITY"] = "security";
  ConfigCategory2["SYSTEM"] = "system";
  ConfigCategory2["MOBILE"] = "mobile";
  ConfigCategory2["WECHAT"] = "wechat";
  return ConfigCategory2;
})(ConfigCategory || {});
var systemConfigs = pgTable(
  "system_configs",
  {
    id: text().primaryKey().notNull(),
    key: text().notNull(),
    value: jsonb().notNull(),
    description: text(),
    createdAt: timestamp({ precision: 3, mode: "string" }).default(sql`CURRENT_TIMESTAMP`).notNull(),
    updatedAt: timestamp({ precision: 3, mode: "string" }).notNull()
  },
  (table) => [
    uniqueIndex("system_configs_key_key").using(
      "btree",
      table.key.asc().nullsLast().op("text_ops")
    )
  ]
);
var configMetadata = pgTable("config_metadata", {
  key: text().primaryKey().notNull(),
  category: text().notNull(),
  type: text().default("string").notNull(),
  isSensitive: boolean().default(false).notNull(),
  isRequired: boolean().default(false).notNull(),
  defaultDescription: text(),
  createdAt: timestamp({ precision: 3, mode: "string" }).default(sql`CURRENT_TIMESTAMP`).notNull(),
  updatedAt: timestamp({ precision: 3, mode: "string" }).notNull()
});
var configDefinitions = pgTable(
  "config_definitions",
  {
    id: integer().primaryKey().generatedAlwaysAsIdentity(),
    key: text().notNull(),
    category: text().notNull(),
    name: text().notNull(),
    description: text(),
    // 类型和验证
    type: text().notNull(),
    // string, number, boolean, json, enum, url, email
    validationRules: jsonb(),
    // 验证规则 JSON
    // UI 配置
    uiComponent: text().default("input"),
    // input, textarea, select, switch, slider
    uiProps: jsonb(),
    // UI 组件属性
    // 安全和权限
    isSensitive: boolean().default(false).notNull(),
    isRequired: boolean().default(false).notNull(),
    isReadonly: boolean().default(false).notNull(),
    requiredPermission: text(),
    // 默认值和选项
    defaultValue: text(),
    enumOptions: jsonb(),
    // 枚举选项
    // 依赖和条件
    dependsOn: text().array(),
    // 依赖的配置项
    showIf: jsonb(),
    // 显示条件
    // 分组和排序
    groupName: text(),
    sortOrder: integer().default(0).notNull(),
    // 版本和状态
    version: integer().default(1).notNull(),
    status: text().default("active").notNull(),
    // active, deprecated, disabled
    // 标签
    tags: text().array(),
    // 元数据
    createdAt: timestamp({ precision: 3, mode: "string" }).default(sql`CURRENT_TIMESTAMP`).notNull(),
    updatedAt: timestamp({ precision: 3, mode: "string" }).default(sql`CURRENT_TIMESTAMP`).notNull(),
    createdBy: integer()
  },
  (table) => [
    uniqueIndex("config_definitions_key_key").using(
      "btree",
      table.key.asc().nullsLast().op("text_ops")
    ),
    index("config_definitions_category_idx").using(
      "btree",
      table.category.asc().nullsLast().op("text_ops")
    ),
    index("config_definitions_status_idx").using(
      "btree",
      table.status.asc().nullsLast().op("text_ops")
    )
  ]
);
var configHistory = pgTable(
  "config_history",
  {
    id: integer().primaryKey().generatedAlwaysAsIdentity(),
    configKey: text().notNull(),
    oldValue: text(),
    newValue: text(),
    changeType: text().notNull(),
    // create, update, delete
    changedBy: integer(),
    changedAt: timestamp({ precision: 3, mode: "string" }).default(sql`CURRENT_TIMESTAMP`).notNull(),
    reason: text(),
    ipAddress: text(),
    userAgent: text()
  },
  (table) => [
    index("config_history_key_idx").using(
      "btree",
      table.configKey.asc().nullsLast().op("text_ops")
    ),
    index("config_history_date_idx").using(
      "btree",
      table.changedAt.asc().nullsLast().op("timestamp_ops")
    )
  ]
);
var defaultLogger = {
  info: (message, ...args) => console.log(`[ConfigEngine] ${message}`, ...args),
  warn: (message, ...args) => console.warn(`[ConfigEngine] ${message}`, ...args),
  error: (message, ...args) => console.error(`[ConfigEngine] ${message}`, ...args)
};
var ConfigEngine = class {
  constructor(options) {
    this.definitionsCache = /* @__PURE__ */ new Map();
    this.initialized = false;
    this.db = options.db;
    this.tables = options.tables;
    this.logger = options.logger || defaultLogger;
    this.encryptionKey = options.encryptionKey || process.env.CONFIG_ENCRYPTION_KEY || "default-config-key-2024";
    if (this.encryptionKey === "default-config-key-2024") {
      this.logger.warn("\u26A0\uFE0F \u4F7F\u7528\u9ED8\u8BA4\u52A0\u5BC6\u5BC6\u94A5\uFF0C\u751F\u4EA7\u73AF\u5883\u8BF7\u8BBE\u7F6E CONFIG_ENCRYPTION_KEY \u73AF\u5883\u53D8\u91CF");
    }
  }
  /**
   * 初始化配置引擎
   */
  async initialize() {
    if (this.initialized) return;
    try {
      await this.loadDefinitions();
      this.initialized = true;
      this.logger.info("\u2705 ConfigEngine \u521D\u59CB\u5316\u6210\u529F");
    } catch (error) {
      this.logger.error("\u274C ConfigEngine \u521D\u59CB\u5316\u5931\u8D25:", error);
      throw error;
    }
  }
  /**
   * 从数据库加载所有配置定义到缓存
   */
  async loadDefinitions() {
    try {
      const definitions = await this.db.select().from(this.tables.configDefinitions).where(eq(this.tables.configDefinitions.status, "active"));
      this.definitionsCache.clear();
      definitions.forEach((def) => {
        const definition = {
          id: def.id,
          key: def.key,
          category: def.category,
          name: def.name,
          description: def.description || void 0,
          type: def.type,
          validationRules: def.validationRules ? JSON.parse(JSON.stringify(def.validationRules)) : void 0,
          uiComponent: def.uiComponent,
          uiProps: def.uiProps ? JSON.parse(JSON.stringify(def.uiProps)) : void 0,
          isSensitive: def.isSensitive,
          isRequired: def.isRequired,
          isReadonly: def.isReadonly,
          requiredPermission: def.requiredPermission || void 0,
          defaultValue: def.defaultValue || void 0,
          enumOptions: def.enumOptions ? JSON.parse(JSON.stringify(def.enumOptions)) : void 0,
          dependsOn: def.dependsOn || void 0,
          showIf: def.showIf ? JSON.parse(JSON.stringify(def.showIf)) : void 0,
          groupName: def.groupName || void 0,
          sortOrder: def.sortOrder,
          version: def.version,
          status: def.status,
          tags: def.tags || void 0,
          createdAt: def.createdAt,
          updatedAt: def.updatedAt,
          createdBy: def.createdBy || void 0
        };
        this.definitionsCache.set(def.key, definition);
      });
      this.logger.info(`\u2705 \u5DF2\u52A0\u8F7D ${definitions.length} \u4E2A\u914D\u7F6E\u5B9A\u4E49`);
    } catch (error) {
      this.logger.error("\u274C \u52A0\u8F7D\u914D\u7F6E\u5B9A\u4E49\u5931\u8D25:", error);
      throw error;
    }
  }
  /**
   * 获取单个配置定义
   */
  getDefinition(key) {
    return this.definitionsCache.get(key);
  }
  /**
   * 获取所有配置定义
   */
  getAllDefinitions() {
    return Array.from(this.definitionsCache.values());
  }
  /**
   * 获取指定分类的配置定义
   */
  getDefinitionsByCategory(category) {
    return this.getAllDefinitions().filter((def) => def.category === category).sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0));
  }
  /**
   * 验证配置值
   */
  async validate(key, value) {
    const definition = this.getDefinition(key);
    if (!definition) {
      return {
        valid: false,
        errors: ["\u914D\u7F6E\u5B9A\u4E49\u4E0D\u5B58\u5728"]
      };
    }
    const errors = [];
    if (definition.isRequired && (value === null || value === void 0 || value === "")) {
      errors.push("\u6B64\u914D\u7F6E\u9879\u4E3A\u5FC5\u586B");
      return { valid: false, errors };
    }
    if (value === null || value === void 0 || value === "") {
      return { valid: true, errors: [] };
    }
    const typeError = this.validateType(value, definition.type);
    if (typeError) {
      errors.push(typeError);
    }
    if (definition.validationRules && typeError === null) {
      const ruleErrors = this.validateRules(value, definition.validationRules);
      errors.push(...ruleErrors);
    }
    return {
      valid: errors.length === 0,
      errors
    };
  }
  /**
   * 获取配置的完整数据（定义 + 值）
   */
  async getConfigsWithValues(category) {
    if (!this.initialized) {
      await this.initialize();
    }
    const definitions = category ? this.getDefinitionsByCategory(category) : this.getAllDefinitions();
    const configValues = await this.db.select().from(this.tables.systemConfigs);
    const valueMap = new Map(configValues.map((v) => [v.key, v.value]));
    const result = definitions.map((def) => {
      let value = valueMap.get(def.key) ?? def.defaultValue;
      let displayValue = value;
      if (def.isSensitive && value && typeof value === "string") {
        try {
          value = this.decrypt(value);
          displayValue = this.maskValue(value);
        } catch (error) {
          this.logger.warn(`\u89E3\u5BC6\u914D\u7F6E ${def.key} \u5931\u8D25:`, error);
        }
      }
      return {
        ...def,
        value,
        displayValue
      };
    });
    return result;
  }
  /**
   * 获取单个配置值
   */
  async getValue(key) {
    const definition = this.getDefinition(key);
    if (!definition) {
      return void 0;
    }
    const configs = await this.db.select().from(this.tables.systemConfigs).where(eq(this.tables.systemConfigs.key, key)).limit(1);
    if (configs.length === 0) {
      return definition.defaultValue;
    }
    let value = configs[0].value;
    if (definition.isSensitive && value && typeof value === "string") {
      try {
        value = this.decrypt(value);
      } catch (error) {
        this.logger.warn(`\u89E3\u5BC6\u914D\u7F6E ${key} \u5931\u8D25:`, error);
      }
    }
    return value;
  }
  /**
   * 设置配置值
   */
  async setValue(key, value, userId = 0, options) {
    const validation = await this.validate(key, value);
    if (!validation.valid) {
      throw new Error(`\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25: ${validation.errors.join(", ")}`);
    }
    const definition = this.getDefinition(key);
    if (!definition) {
      throw new Error("\u914D\u7F6E\u5B9A\u4E49\u4E0D\u5B58\u5728");
    }
    const oldConfigs = await this.db.select().from(this.tables.systemConfigs).where(eq(this.tables.systemConfigs.key, key)).limit(1);
    const oldValue = oldConfigs.length > 0 ? oldConfigs[0].value : void 0;
    let finalValue = value;
    if (definition.isSensitive && value) {
      finalValue = this.encrypt(String(value));
    }
    if (oldConfigs.length > 0) {
      await this.db.update(this.tables.systemConfigs).set({
        value: finalValue,
        updatedAt: (/* @__PURE__ */ new Date()).toISOString()
      }).where(eq(this.tables.systemConfigs.key, key));
    } else {
      const id = crypto.randomUUID();
      await this.db.insert(this.tables.systemConfigs).values({
        id,
        key,
        value: finalValue,
        description: definition.description,
        createdAt: (/* @__PURE__ */ new Date()).toISOString(),
        updatedAt: (/* @__PURE__ */ new Date()).toISOString()
      });
    }
    await this.recordHistory({
      configKey: key,
      oldValue: oldValue ? JSON.stringify(oldValue) : void 0,
      newValue: JSON.stringify(value),
      changeType: oldValue ? "update" : "create",
      changedBy: userId,
      reason: options?.reason,
      ipAddress: options?.ipAddress,
      userAgent: options?.userAgent
    });
    this.logger.info(`\u2705 \u914D\u7F6E\u5DF2${oldValue ? "\u66F4\u65B0" : "\u521B\u5EFA"}: ${key}`);
  }
  /**
   * 批量设置配置值
   */
  async setValues(values, userId = 0, options) {
    for (const item of values) {
      await this.setValue(item.key, item.value, userId, options);
    }
  }
  /**
   * 注册新配置定义
   */
  async registerDefinition(definition, userId = 0) {
    try {
      await this.db.insert(this.tables.configDefinitions).values({
        key: definition.key,
        category: definition.category,
        name: definition.name,
        description: definition.description,
        type: definition.type,
        validationRules: definition.validationRules ? JSON.stringify(definition.validationRules) : null,
        uiComponent: definition.uiComponent || "input",
        uiProps: definition.uiProps ? JSON.stringify(definition.uiProps) : null,
        isSensitive: definition.isSensitive || false,
        isRequired: definition.isRequired || false,
        isReadonly: definition.isReadonly || false,
        requiredPermission: definition.requiredPermission,
        defaultValue: definition.defaultValue,
        enumOptions: definition.enumOptions ? JSON.stringify(definition.enumOptions) : null,
        dependsOn: definition.dependsOn,
        showIf: definition.showIf ? JSON.stringify(definition.showIf) : null,
        groupName: definition.groupName,
        sortOrder: definition.sortOrder || 0,
        version: definition.version || 1,
        status: definition.status || "active",
        tags: definition.tags,
        createdBy: userId,
        updatedAt: (/* @__PURE__ */ new Date()).toISOString()
      });
      await this.loadDefinitions();
      this.logger.info(`\u2705 \u6CE8\u518C\u65B0\u914D\u7F6E\u5B9A\u4E49: ${definition.key}`);
    } catch (error) {
      this.logger.error(`\u274C \u6CE8\u518C\u914D\u7F6E\u5B9A\u4E49\u5931\u8D25:`, error);
      throw error;
    }
  }
  /**
   * 批量注册配置定义
   */
  async registerDefinitions(definitions, userId = 0) {
    for (const definition of definitions) {
      await this.registerDefinition(definition, userId);
    }
  }
  /**
   * 记录配置变更历史
   */
  async recordHistory(record) {
    try {
      await this.db.insert(this.tables.configHistory).values({
        ...record,
        changedAt: (/* @__PURE__ */ new Date()).toISOString()
      });
    } catch (error) {
      this.logger.error("\u274C \u8BB0\u5F55\u914D\u7F6E\u5386\u53F2\u5931\u8D25:", error);
    }
  }
  /**
   * 获取配置变更历史
   */
  async getHistory(key, limit = 50) {
    try {
      const history = await this.db.select().from(this.tables.configHistory).where(eq(this.tables.configHistory.configKey, key)).orderBy(this.tables.configHistory.changedAt).limit(limit);
      return history;
    } catch (error) {
      this.logger.error("\u274C \u83B7\u53D6\u914D\u7F6E\u5386\u53F2\u5931\u8D25:", error);
      return [];
    }
  }
  // ==================== 私有辅助方法 ====================
  /**
   * 类型验证
   */
  validateType(value, type) {
    switch (type) {
      case "string":
        return typeof value === "string" ? null : "\u503C\u5FC5\u987B\u662F\u5B57\u7B26\u4E32";
      case "number":
        return typeof value === "number" && !isNaN(value) ? null : "\u503C\u5FC5\u987B\u662F\u6570\u5B57";
      case "boolean":
        return typeof value === "boolean" ? null : "\u503C\u5FC5\u987B\u662F\u5E03\u5C14\u503C";
      case "json":
        try {
          if (typeof value === "string") {
            JSON.parse(value);
          }
          return null;
        } catch {
          return "\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684 JSON";
        }
      case "url":
        try {
          new URL(value);
          return null;
        } catch {
          return "\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684 URL";
        }
      case "email":
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) ? null : "\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u90AE\u7BB1\u5730\u5740";
      case "enum":
        return null;
      // 枚举验证在规则验证中处理
      default:
        return null;
    }
  }
  /**
   * 规则验证
   */
  validateRules(value, rules) {
    const errors = [];
    if (rules.min !== void 0 && value < rules.min) {
      errors.push(`\u503C\u4E0D\u80FD\u5C0F\u4E8E ${rules.min}`);
    }
    if (rules.max !== void 0 && value > rules.max) {
      errors.push(`\u503C\u4E0D\u80FD\u5927\u4E8E ${rules.max}`);
    }
    if (rules.minLength !== void 0 && String(value).length < rules.minLength) {
      errors.push(`\u957F\u5EA6\u4E0D\u80FD\u5C0F\u4E8E ${rules.minLength}`);
    }
    if (rules.maxLength !== void 0 && String(value).length > rules.maxLength) {
      errors.push(`\u957F\u5EA6\u4E0D\u80FD\u5927\u4E8E ${rules.maxLength}`);
    }
    if (rules.pattern && !new RegExp(rules.pattern).test(String(value))) {
      errors.push("\u503C\u4E0D\u7B26\u5408\u8981\u6C42\u7684\u683C\u5F0F");
    }
    return errors;
  }
  /**
   * 加密
   */
  encrypt(value) {
    const algorithm = "aes-256-cbc";
    const key = crypto.scryptSync(this.encryptionKey, "salt", 32);
    const iv = crypto.randomBytes(16);
    const cipher = crypto.createCipheriv(algorithm, key, iv);
    let encrypted = cipher.update(value, "utf8", "hex");
    encrypted += cipher.final("hex");
    return iv.toString("hex") + ":" + encrypted;
  }
  /**
   * 解密
   */
  decrypt(encrypted) {
    const algorithm = "aes-256-cbc";
    const key = crypto.scryptSync(this.encryptionKey, "salt", 32);
    const parts = encrypted.split(":");
    if (parts.length !== 2 || !parts[0] || !parts[1]) {
      throw new Error("\u65E0\u6548\u7684\u52A0\u5BC6\u6570\u636E\u683C\u5F0F");
    }
    const [ivHex, encryptedData] = parts;
    const iv = Buffer.from(ivHex, "hex");
    const decipher = crypto.createDecipheriv(algorithm, key, iv);
    let decrypted = decipher.update(encryptedData, "hex", "utf8");
    decrypted += decipher.final("utf8");
    return decrypted;
  }
  /**
   * 掩码显示敏感值
   */
  maskValue(value) {
    if (!value) return "";
    const len = value.length;
    if (len <= 8) {
      return "*".repeat(len);
    }
    return value.substring(0, 4) + "*".repeat(len - 8) + value.substring(len - 4);
  }
};
var defaultLogger2 = {
  info: (message, ...args) => console.log(`[ConfigService] ${message}`, ...args),
  warn: (message, ...args) => console.warn(`[ConfigService] ${message}`, ...args),
  error: (message, ...args) => console.error(`[ConfigService] ${message}`, ...args)
};
var ConfigService = class {
  constructor(options) {
    this.configCache = /* @__PURE__ */ new Map();
    this.metadataCache = /* @__PURE__ */ new Map();
    this.db = options.db;
    this.tables = options.tables;
    this.logger = options.logger || defaultLogger2;
    this.templates = options.templates || {};
    this.encryptionKey = options.encryptionKey || process.env.CONFIG_ENCRYPTION_KEY || "default-config-key-2024";
    this.loadConfigsFromDatabase();
    this.loadMetadataFromDatabase();
  }
  // 从数据库加载元数据
  async loadMetadataFromDatabase() {
    if (!this.tables.configMetadata) {
      this.logger.info("\u914D\u7F6E\u5143\u6570\u636E\u8868\u672A\u63D0\u4F9B\uFF0C\u8DF3\u8FC7\u5143\u6570\u636E\u52A0\u8F7D");
      return;
    }
    try {
      const metadata = await this.db.select().from(this.tables.configMetadata);
      metadata.forEach((meta) => {
        this.metadataCache.set(meta.key, {
          category: meta.category,
          type: meta.type,
          isSensitive: meta.isSensitive,
          isRequired: meta.isRequired,
          defaultDescription: meta.defaultDescription || void 0
        });
      });
      this.logger.info(`\u5DF2\u52A0\u8F7D ${metadata.length} \u6761\u914D\u7F6E\u5143\u6570\u636E`);
    } catch (error) {
      this.logger.warn(
        "\u914D\u7F6E\u5143\u6570\u636E\u8868\u4E0D\u5B58\u5728\uFF0C\u4F7F\u7528\u6A21\u677F\u6570\u636E",
        error instanceof Error ? error.message : String(error)
      );
    }
  }
  // 从数据库加载配置到缓存
  async loadConfigsFromDatabase() {
    try {
      const configs = await this.db.select().from(this.tables.systemConfigs);
      configs.forEach((config) => {
        let value = config.value;
        if (this.isSensitiveConfig(config.key)) {
          try {
            value = this.decrypt(config.value);
            this.logger.info(`\u2705 \u6210\u529F\u89E3\u5BC6\u914D\u7F6E: ${config.key}`);
          } catch (error) {
            this.logger.error(`\u274C \u89E3\u5BC6\u914D\u7F6E\u5931\u8D25: ${config.key}`, error);
            return;
          }
        }
        this.configCache.set(config.key, value);
      });
      this.logger.info(`\u5DF2\u52A0\u8F7D ${configs.length} \u4E2A\u914D\u7F6E\u9879`);
    } catch (error) {
      this.logger.error("\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25", error instanceof Error ? error : new Error(String(error)));
    }
  }
  // 获取配置值
  async getConfig(key, defaultValue) {
    if (!key) {
      return defaultValue;
    }
    const envValue = process.env[key.toUpperCase()];
    if (envValue !== void 0) {
      return this.parseValue(envValue, this.getConfigType(key));
    }
    if (this.configCache.has(key)) {
      return this.configCache.get(key);
    }
    try {
      const [config] = await this.db.select().from(this.tables.systemConfigs).where(eq(this.tables.systemConfigs.key, key)).limit(1);
      if (config) {
        let value = config.value;
        if (this.isSensitiveConfig(key)) {
          try {
            value = this.decrypt(config.value);
            this.logger.info(`\u2705 \u6210\u529F\u89E3\u5BC6\u914D\u7F6E: ${key}, \u957F\u5EA6: ${value?.length}`);
          } catch (error) {
            this.logger.error(`\u274C \u89E3\u5BC6\u914D\u7F6E\u5931\u8D25: ${key}`, error);
            throw new Error(`\u914D\u7F6E ${key} \u89E3\u5BC6\u5931\u8D25`);
          }
        }
        this.configCache.set(key, value);
        return value;
      }
    } catch (error) {
      this.logger.error(
        `\u83B7\u53D6\u914D\u7F6E ${key} \u5931\u8D25`,
        error instanceof Error ? error : new Error(String(error))
      );
    }
    return defaultValue;
  }
  // 设置配置值
  async setConfig(key, value, description) {
    try {
      const category = this.getConfigCategory(key);
      const type = this.getConfigType(key);
      const isSensitive = this.isSensitiveConfig(key);
      const validatedValue = this.validateValue(value, type);
      const storageValue = isSensitive ? this.encrypt(validatedValue) : validatedValue;
      const existing = await this.db.select().from(this.tables.systemConfigs).where(eq(this.tables.systemConfigs.key, key)).limit(1);
      if (existing.length > 0) {
        await this.db.update(this.tables.systemConfigs).set({
          value: storageValue,
          description: description || this.getConfigDescription(key),
          updatedAt: (/* @__PURE__ */ new Date()).toISOString()
        }).where(eq(this.tables.systemConfigs.key, key));
      } else {
        await this.db.insert(this.tables.systemConfigs).values({
          id: crypto__default.randomBytes(16).toString("hex"),
          key,
          value: storageValue,
          description: description || this.getConfigDescription(key),
          createdAt: (/* @__PURE__ */ new Date()).toISOString(),
          updatedAt: (/* @__PURE__ */ new Date()).toISOString()
        });
      }
      this.configCache.set(key, validatedValue);
      this.logger.info(`\u914D\u7F6E ${key} \u5DF2\u66F4\u65B0`);
    } catch (error) {
      this.logger.error(
        `\u8BBE\u7F6E\u914D\u7F6E ${key} \u5931\u8D25`,
        error instanceof Error ? error : new Error(String(error))
      );
      throw error;
    }
  }
  // 获取分类下的所有配置
  async getConfigsByCategory(category) {
    const configs = {};
    const template = this.templates[category] || [];
    for (const item of template) {
      configs[item.key] = await this.getConfig(item.key, item.defaultValue);
    }
    return configs;
  }
  // 批量设置配置
  async setConfigs(configs) {
    for (const [key, value] of Object.entries(configs)) {
      await this.setConfig(key, value);
    }
  }
  // 删除配置
  async deleteConfig(key) {
    try {
      await this.db.delete(this.tables.systemConfigs).where(eq(this.tables.systemConfigs.key, key));
      this.configCache.delete(key);
      this.logger.info(`\u914D\u7F6E ${key} \u5DF2\u5220\u9664`);
    } catch (error) {
      this.logger.error(
        `\u5220\u9664\u914D\u7F6E ${key} \u5931\u8D25`,
        error instanceof Error ? error : new Error(String(error))
      );
      throw error;
    }
  }
  // 获取所有配置（用于管理界面）
  async getAllConfigs() {
    const allConfigs = {};
    const dbConfigs = await this.db.select().from(this.tables.systemConfigs);
    const dbConfigKeys = new Set(dbConfigs.map((c) => c.key));
    for (const [category, items] of Object.entries(this.templates)) {
      allConfigs[category] = {};
      for (const item of items) {
        if (dbConfigKeys.has(item.key)) {
          const value = await this.getConfig(item.key, item.defaultValue);
          allConfigs[category][item.key] = {
            ...item,
            value: item.isSensitive ? "" : value,
            // 敏感信息隐藏
            isStored: true
            // 标记为已存储
          };
        }
      }
    }
    return allConfigs;
  }
  // 刷新配置缓存
  async refreshCache() {
    this.configCache.clear();
    await this.loadConfigsFromDatabase();
  }
  // 配置验证
  validateConfig(key, value) {
    const type = this.getConfigType(key);
    const isRequired = this.isRequiredConfig(key);
    if (isRequired && (value === void 0 || value === null || value === "")) {
      throw new Error(`\u914D\u7F6E ${key} \u662F\u5FC5\u9700\u7684`);
    }
    try {
      this.validateValue(value, type);
      return true;
    } catch (error) {
      throw new Error(`\u914D\u7F6E ${key} \u503C\u65E0\u6548: ${error.message}`);
    }
  }
  // 私有方法：加密
  encrypt(text2) {
    const algorithm = "aes-256-cbc";
    const key = crypto__default.scryptSync(this.encryptionKey, "salt", 32);
    const iv = crypto__default.randomBytes(16);
    const cipher = crypto__default.createCipheriv(algorithm, key, iv);
    let encrypted = cipher.update(text2, "utf8", "hex");
    encrypted += cipher.final("hex");
    return iv.toString("hex") + ":" + encrypted;
  }
  // 私有方法：解密
  decrypt(encryptedText) {
    const algorithm = "aes-256-cbc";
    const key = crypto__default.scryptSync(this.encryptionKey, "salt", 32);
    const parts = encryptedText.split(":");
    if (parts.length !== 2 || !parts[0] || !parts[1]) {
      throw new Error("\u65E0\u6548\u7684\u52A0\u5BC6\u6570\u636E\u683C\u5F0F");
    }
    const iv = Buffer.from(parts[0], "hex");
    const encrypted = parts[1];
    const decipher = crypto__default.createDecipheriv(algorithm, key, iv);
    let decrypted = decipher.update(encrypted, "hex", "utf8");
    decrypted += decipher.final("utf8");
    return decrypted;
  }
  // 私有方法：解析值类型
  parseValue(value, type) {
    switch (type) {
      case "number":
        return parseInt(value);
      case "boolean":
        return value.toLowerCase() === "true";
      case "json":
        return JSON.parse(value);
      default:
        return value;
    }
  }
  // 私有方法：验证值
  validateValue(value, type) {
    switch (type) {
      case "string":
        return String(value);
      case "number":
        const num = Number(value);
        if (isNaN(num)) throw new Error("\u503C\u5FC5\u987B\u662F\u6570\u5B57");
        return num;
      case "boolean":
        return Boolean(value);
      case "json":
        if (typeof value === "string") {
          return JSON.parse(value);
        }
        return value;
      default:
        return value;
    }
  }
  // 私有方法：获取配置类型
  getConfigType(key) {
    const metadata = this.metadataCache.get(key);
    return metadata?.type || "string";
  }
  // 私有方法：获取配置分类
  getConfigCategory(key) {
    const metadata = this.metadataCache.get(key);
    return metadata?.category || "system" /* SYSTEM */;
  }
  // 私有方法：检查是否为敏感配置
  isSensitiveConfig(key) {
    const metadata = this.metadataCache.get(key);
    return metadata?.isSensitive || false;
  }
  // 私有方法：检查是否为必需配置
  isRequiredConfig(key) {
    const metadata = this.metadataCache.get(key);
    return metadata?.isRequired || false;
  }
  // 私有方法：获取配置描述
  getConfigDescription(key) {
    const metadata = this.metadataCache.get(key);
    return metadata?.defaultDescription || "";
  }
  // 新增方法：创建或更新配置元数据
  async setConfigMetadata(key, category, type = "string", options = {}) {
    if (!this.tables.configMetadata) {
      this.logger.warn("\u914D\u7F6E\u5143\u6570\u636E\u8868\u672A\u63D0\u4F9B\uFF0C\u8DF3\u8FC7\u5143\u6570\u636E\u8BBE\u7F6E");
      return;
    }
    try {
      const now = (/* @__PURE__ */ new Date()).toISOString();
      const existing = await this.db.select().from(this.tables.configMetadata).where(eq(this.tables.configMetadata.key, key)).limit(1);
      if (existing.length > 0) {
        await this.db.update(this.tables.configMetadata).set({
          category,
          type,
          isSensitive: options.isSensitive ?? false,
          isRequired: options.isRequired ?? false,
          defaultDescription: options.defaultDescription,
          updatedAt: now
        }).where(eq(this.tables.configMetadata.key, key));
      } else {
        await this.db.insert(this.tables.configMetadata).values({
          key,
          category,
          type,
          isSensitive: options.isSensitive ?? false,
          isRequired: options.isRequired ?? false,
          defaultDescription: options.defaultDescription,
          createdAt: now,
          updatedAt: now
        });
      }
      this.metadataCache.set(key, {
        category,
        type,
        isSensitive: options.isSensitive ?? false,
        isRequired: options.isRequired ?? false,
        defaultDescription: options.defaultDescription
      });
      this.logger.info(`\u914D\u7F6E\u5143\u6570\u636E ${key} \u5DF2\u66F4\u65B0`);
    } catch (error) {
      this.logger.error(
        `\u8BBE\u7F6E\u914D\u7F6E\u5143\u6570\u636E ${key} \u5931\u8D25`,
        error instanceof Error ? error : new Error(String(error))
      );
      throw error;
    }
  }
};
function createConfigService(options) {
  return new ConfigService(options);
}

// src/config/server/templates.ts
var DEFAULT_CONFIG_TEMPLATES = {
  // 数据库相关的业务配置（非连接配置）
  ["database" /* DATABASE */]: [
    {
      key: "database_pool_size",
      value: 10,
      category: "database" /* DATABASE */,
      type: "number",
      isRequired: false,
      isSensitive: false,
      description: "\u6570\u636E\u5E93\u8FDE\u63A5\u6C60\u5927\u5C0F",
      defaultValue: 10,
      group: "\u8FDE\u63A5\u6C60\u914D\u7F6E"
    },
    {
      key: "database_query_timeout",
      value: 3e4,
      category: "database" /* DATABASE */,
      type: "number",
      isRequired: false,
      isSensitive: false,
      description: "\u6570\u636E\u5E93\u67E5\u8BE2\u8D85\u65F6\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09",
      defaultValue: 3e4,
      group: "\u8FDE\u63A5\u6C60\u914D\u7F6E"
    },
    {
      key: "enable_query_logging",
      value: false,
      category: "database" /* DATABASE */,
      type: "boolean",
      isRequired: false,
      isSensitive: false,
      description: "\u542F\u7528\u6570\u636E\u5E93\u67E5\u8BE2\u65E5\u5FD7",
      defaultValue: false,
      group: "\u8FDE\u63A5\u6C60\u914D\u7F6E"
    }
  ],
  // 存储配置
  ["storage" /* STORAGE */]: [
    {
      key: "storage_type",
      value: "local",
      category: "storage" /* STORAGE */,
      type: "string",
      isRequired: true,
      isSensitive: false,
      description: "\u5B58\u50A8\u7C7B\u578B\uFF08local/aliyun-oss/aws-s3\uFF09",
      defaultValue: "local",
      group: "\u57FA\u7840\u914D\u7F6E"
    },
    {
      key: "upload_max_size",
      value: 10485760,
      category: "storage" /* STORAGE */,
      type: "number",
      isRequired: false,
      isSensitive: false,
      description: "\u6700\u5927\u4E0A\u4F20\u6587\u4EF6\u5927\u5C0F\uFF08\u5B57\u8282\uFF09",
      defaultValue: 10485760,
      group: "\u4E0A\u4F20\u914D\u7F6E"
    }
  ],
  // 安全配置
  ["security" /* SECURITY */]: [
    {
      key: "jwt_secret",
      value: "",
      category: "security" /* SECURITY */,
      type: "string",
      isRequired: true,
      isSensitive: true,
      description: "JWT\u7B7E\u540D\u5BC6\u94A5"
    },
    {
      key: "jwt_expires_in",
      value: "7d",
      category: "security" /* SECURITY */,
      type: "string",
      isRequired: true,
      isSensitive: false,
      description: "JWT\u8FC7\u671F\u65F6\u95F4",
      defaultValue: "7d"
    },
    {
      key: "enable_rate_limiting",
      value: true,
      category: "security" /* SECURITY */,
      type: "boolean",
      isRequired: false,
      isSensitive: false,
      description: "\u542F\u7528API\u901F\u7387\u9650\u5236",
      defaultValue: true
    }
  ],
  // 系统配置
  ["system" /* SYSTEM */]: [
    {
      key: "app_name",
      value: "My App",
      category: "system" /* SYSTEM */,
      type: "string",
      isRequired: true,
      isSensitive: false,
      description: "\u5E94\u7528\u540D\u79F0",
      defaultValue: "My App"
    },
    {
      key: "maintenance_mode",
      value: false,
      category: "system" /* SYSTEM */,
      type: "boolean",
      isRequired: false,
      isSensitive: false,
      description: "\u7EF4\u62A4\u6A21\u5F0F",
      defaultValue: false
    },
    {
      key: "log_level",
      value: "info",
      category: "system" /* SYSTEM */,
      type: "string",
      isRequired: false,
      isSensitive: false,
      description: "\u65E5\u5FD7\u7EA7\u522B",
      defaultValue: "info"
    }
  ]
};
function createConfigTemplates(templates) {
  const filteredTemplates = { ...DEFAULT_CONFIG_TEMPLATES };
  Object.keys(templates).forEach((key) => {
    const value = templates[key];
    if (value !== void 0) {
      filteredTemplates[key] = value;
    }
  });
  return filteredTemplates;
}

// src/config/server/factory.ts
function createConfigEngine(options) {
  return new ConfigEngine(options);
}
function createGlobalConfigService(options) {
  let instance = null;
  return () => {
    if (!instance) {
      instance = new ConfigService(options);
    }
    return instance;
  };
}
function createGlobalConfigEngine(options) {
  let instance = null;
  let isInitializing = false;
  return () => {
    if (!instance) {
      instance = new ConfigEngine(options);
      if (!isInitializing) {
        isInitializing = true;
        instance.initialize().catch((error) => {
          console.error("[ConfigEngine] \u521D\u59CB\u5316\u5931\u8D25:", error);
        });
      }
    }
    return instance;
  };
}

// src/config/server/database-config.ts
function getDatabaseConfig() {
  const databaseUrl = process.env.DATABASE_URL;
  if (databaseUrl) {
    const url = new URL(databaseUrl);
    return {
      host: url.hostname,
      port: parseInt(url.port) || 5432,
      database: url.pathname.slice(1),
      // 移除开头的 /
      username: url.username,
      password: url.password,
      ssl: url.searchParams.get("sslmode") === "require",
      poolSize: parseInt(process.env.DB_POOL_SIZE || "10"),
      queryTimeout: parseInt(process.env.DB_QUERY_TIMEOUT || "30000")
    };
  }
  return {
    host: process.env.DB_HOST || process.env.POSTGRES_HOST || "localhost",
    port: parseInt(process.env.DB_PORT || process.env.POSTGRES_PORT || "5432"),
    database: process.env.DB_NAME || process.env.POSTGRES_DB || "lyricnote",
    username: process.env.DB_USER || process.env.POSTGRES_USER || "lyricnote",
    password: process.env.DB_PASSWORD || process.env.POSTGRES_PASSWORD || "",
    ssl: process.env.DB_SSL === "true",
    poolSize: parseInt(process.env.DB_POOL_SIZE || "10"),
    queryTimeout: parseInt(process.env.DB_QUERY_TIMEOUT || "30000")
  };
}
function getRedisConfig() {
  const redisUrl = process.env.REDIS_URL;
  if (redisUrl) {
    const url = new URL(redisUrl);
    return {
      host: url.hostname,
      port: parseInt(url.port) || 6379,
      password: url.password || void 0,
      database: parseInt(url.pathname.slice(1)) || 0,
      keyPrefix: process.env.REDIS_KEY_PREFIX || "lyricnote:"
    };
  }
  return {
    host: process.env.REDIS_HOST || "localhost",
    port: parseInt(process.env.REDIS_PORT || "6379"),
    password: process.env.REDIS_PASSWORD || void 0,
    database: parseInt(process.env.REDIS_DB || "0"),
    keyPrefix: process.env.REDIS_KEY_PREFIX || "lyricnote:"
  };
}
function buildDatabaseUrl(config) {
  const { host, port, database, username, password, ssl } = config;
  let url = `postgresql://${username}:${password}@${host}:${port}/${database}`;
  if (ssl) {
    url += "?sslmode=require";
  }
  return url;
}
function buildRedisUrl(config) {
  const { host, port, password, database } = config;
  let url = `redis://`;
  if (password) {
    url += `:${password}@`;
  }
  url += `${host}:${port}`;
  if (database && database !== 0) {
    url += `/${database}`;
  }
  return url;
}
function validateDatabaseConfig(config) {
  const errors = [];
  if (!config.host) errors.push("\u6570\u636E\u5E93\u4E3B\u673A\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A");
  if (!config.port || config.port < 1 || config.port > 65535) errors.push("\u6570\u636E\u5E93\u7AEF\u53E3\u53F7\u65E0\u6548");
  if (!config.database) errors.push("\u6570\u636E\u5E93\u540D\u4E0D\u80FD\u4E3A\u7A7A");
  if (!config.username) errors.push("\u6570\u636E\u5E93\u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A");
  if (!config.password) errors.push("\u6570\u636E\u5E93\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A");
  return errors;
}
function getDatabaseConfigForDisplay() {
  const config = getDatabaseConfig();
  return {
    // 只显示非敏感信息
    host: config.host,
    port: config.port,
    database: config.database,
    username: config.username,
    password: config.password ? "***" : "",
    ssl: config.ssl || false,
    poolSize: config.poolSize,
    queryTimeout: config.queryTimeout,
    // 连接状态
    connectionString: `postgresql://${config.username}:***@${config.host}:${config.port}/${config.database}`,
    source: process.env.DATABASE_URL ? "DATABASE_URL" : "Environment Variables"
  };
}

export { ConfigCategory, ConfigEngine, ConfigService, DEFAULT_CONFIG_TEMPLATES, buildDatabaseUrl, buildRedisUrl, configDefinitions, configHistory, configMetadata, createConfigEngine, createConfigService, createConfigTemplates, createGlobalConfigEngine, createGlobalConfigService, getDatabaseConfig, getDatabaseConfigForDisplay, getRedisConfig, systemConfigs, validateDatabaseConfig };
//# sourceMappingURL=index.mjs.map
//# sourceMappingURL=index.mjs.map