/**
 * DatabaseConfigStore 使用示例
 * 
 * 示例代码展示如何使用 DatabaseConfigStore 管理数据库配置
 */

// ============================================================================
// 示例 1: 使用 InMemory 存储（默认）
// ============================================================================

import {
  storeLatticeManager,
  InMemoryDatabaseConfigStore,
} from '@axiom-lattice/core';
import type { DatabaseConfig } from '@axiom-lattice/protocols';

async function exampleInMemory() {
  // 获取默认的 InMemory Store
  const store = await storeLatticeManager.getStoreLattice('default', 'database').store;
  
  const tenantId = 'tenant-123';
  
  // 创建数据库配置
  const dbConfig: DatabaseConfig = {
    type: 'postgres',
    host: 'localhost',
    port: 5432,
    database: 'mydb',
    user: 'admin',
    password: 'secret123',  // 会自动加密存储（PG 实现）
  };
  
  await store.createConfig(tenantId, 'config-1', {
    key: 'main-db',
    config: dbConfig,
    name: 'Main Database',
    description: 'Primary PostgreSQL database',
  });
  
  // 获取配置
  const config = await store.getConfigByKey(tenantId, 'main-db');
  console.log('Database config:', config);
  
  // 获取所有配置
  const allConfigs = await store.getAllConfigs(tenantId);
  console.log('All configs:', allConfigs);
}

// ============================================================================
// 示例 2: 使用 PostgreSQL 存储
// ============================================================================

import { PostgreSQLDatabaseConfigStore } from '@axiom-lattice/pg-stores';

async function examplePostgreSQL() {
  // 创建 PostgreSQL Store
  const pgStore = new PostgreSQLDatabaseConfigStore({
    poolConfig: process.env.DATABASE_URL || 'postgresql://localhost:5432/lattice',
    autoMigrate: true,  // 自动运行迁移
  });
  
  const tenantId = 'tenant-123';
  
  // 创建数据库配置
  await pgStore.createConfig(tenantId, 'config-2', {
    key: 'analytics-db',
    config: {
      type: 'postgres',
      host: 'analytics.db',
      port: 5432,
      database: 'analytics',
      user: 'analyst',
      password: 'analytics-pass',
      ssl: true,
    },
    name: 'Analytics Database',
  });
  
  // 获取配置（密码会自动解密）
  const config = await pgStore.getConfigByKey(tenantId, 'analytics-db');
  console.log('Analytics DB password (decrypted):', config?.config.password);
  
  // 更新配置
  await pgStore.updateConfig(tenantId, 'config-2', {
    config: {
      ...config!.config,
      password: 'new-password',
    },
  });
  
  // 删除配置
  await pgStore.deleteConfig(tenantId, 'config-2');
  
  // 清理资源
  await pgStore.dispose();
}

// ============================================================================
// 示例 3: 集成到 SqlDatabaseManager
// ============================================================================

import { sqlDatabaseManager } from '@axiom-lattice/core';

async function exampleWithSqlManager() {
  const tenantId = 'tenant-123';
  
  // Store is auto-read from StoreLatticeManager by SqlDatabaseManager — no setConfigStore needed
  
  // 现在可以使用注册的数据库（会自动从 store 加载）
  const db = await sqlDatabaseManager.getDatabase(tenantId, 'main-db');
  const tables = await db.listTables();
  console.log('Tables:', tables);
}

// ============================================================================
// 示例 4: 多租户场景
// ============================================================================

async function exampleMultiTenant() {
  const store = await storeLatticeManager.getStoreLattice('default', 'database').store;
  
  // 为不同租户创建配置
  await store.createConfig('tenant-a', 'config-1', {
    key: 'db',
    config: { type: 'postgres', database: 'db-a', user: 'user-a', password: 'pass-a' },
  });
  
  await store.createConfig('tenant-b', 'config-1', {
    key: 'db',
    config: { type: 'postgres', database: 'db-b', user: 'user-b', password: 'pass-b' },
  });
  
  // 获取租户 A 的配置
  const tenantAConfigs = await store.getAllConfigs('tenant-a');
  console.log('Tenant A configs:', tenantAConfigs);
  
  // 获取租户 B 的配置
  const tenantBConfigs = await store.getAllConfigs('tenant-b');
  console.log('Tenant B configs:', tenantBConfigs);
}

// ============================================================================
// 示例 5: 环境变量配置
// ============================================================================

/**
 * 设置加密密钥（生产环境必需）
 * 
 * 方法 1: 环境变量
 * export LATTICE_ENCRYPTION_KEY="your-secret-key-at-least-32-characters"
 * 
 * 方法 2: 代码中设置（不推荐，仅用于测试）
 * process.env.LATTICE_ENCRYPTION_KEY = 'your-secret-key';
 * 
 * 注意：
 * - 密钥长度建议 32 字符以上
 * - 生产环境必须设置，否则会有警告
 * - 密钥丢失将导致无法解密已存储的密码
 */

// ============================================================================
// 运行示例
// ============================================================================

async function main() {
  try {
    await exampleInMemory();
    await examplePostgreSQL();
    await exampleWithSqlManager();
    await exampleMultiTenant();
  } catch (error) {
    console.error('Error running examples:', error);
  }
}

// main();
