import { logger } from '../utils/logger';
import db from '../config/database';

export default class DatabaseSchema {
  static async initAllTables(): Promise<void> {
    await this.initTenantTable();
    await this.initShopTable();
    await this.initUserTable();
    await this.initRoleTable();
    await this.initPermissionTable();
    await this.initRolePermissionTable();
    await this.initUserRoleTable();
    await this.initProductTable();
    await this.initOrderTable();
    await this.initOrderItemTable();
    await this.initAdvertisementTable();
    await this.initAdMetricsTable();
    await this.initCertificateTable();
    await this.initComplianceRuleTable();
    await this.initAuditLogTable();
    await this.initSecurityTables();
    await this.initTestTables();
    await this.initMerchantMetricsTable();
    await this.initLeaderboardSnapshotTable();
    await this.initStrategiesTable();
    await this.initMerchantStrategiesTable();
    await this.initAutopilotSessionsTable();
    await this.initAutopilotLogsTable();
    await this.initPriceComparisonsTable();
    await this.initArbitrageOpportunitiesTable();
    await this.initArbitrageExecutionsTable();
    await this.initPricingTables();
    await this.initCompetitorPriceTables();
    await this.initCurrencyTables();
    
    logger.info('[DatabaseSchema] All tables initialized successfully');
  }

  // 租户表
  private static async initTenantTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_tenant');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_tenant table...');
      await db.schema.createTable('cf_tenant', (table) => {
        table.string('id', 36).primary();
        table.string('name', 128).notNullable().unique();
        table.string('domain', 128).notNullable().unique();
        table.string('contact_name', 64).notNullable();
        table.string('contact_email', 128).notNullable().unique();
        table.string('contact_phone', 32).notNullable();
        table.string('address', 255).notNullable();
        table.enum('status', ['ACTIVE', 'INACTIVE', 'SUSPENDED']).defaultTo('ACTIVE');
        table.decimal('quota_limit', 10, 2).defaultTo(10000);
        table.decimal('quota_used', 10, 2).defaultTo(0);
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.index('domain');
        table.index('status');
      });
      logger.info('[DatabaseSchema] Table cf_tenant created');
    }
  }

  // 店铺表
  private static async initShopTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_shop');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_shop table...');
      await db.schema.createTable('cf_shop', (table) => {
        table.string('id', 36).primary();
        table.string('tenant_id', 36).notNullable().index();
        table.string('name', 128).notNullable();
        table.string('platform', 32).notNullable();
        table.string('platform_shop_id', 128).notNullable();
        table.string('api_key', 255).notNullable();
        table.string('api_secret', 255).notNullable();
        table.string('access_token', 255);
        table.datetime('token_expires_at');
        table.enum('status', ['ACTIVE', 'INACTIVE', 'SYNCING', 'ERROR']).defaultTo('INACTIVE');
        table.string('last_sync_by', 36);
        table.datetime('last_sync_at');
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.unique(['platform', 'platform_shop_id']);
        table.foreign('tenant_id').references('id').inTable('cf_tenant').onDelete('CASCADE');
      });
      logger.info('[DatabaseSchema] Table cf_shop created');
    }
  }

  // 用户表
  private static async initUserTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_user');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_user table...');
      await db.schema.createTable('cf_user', (table) => {
        table.string('id', 36).primary();
        table.string('tenant_id', 36).notNullable().index();
        table.string('username', 64).notNullable().unique();
        table.string('email', 128).notNullable().unique();
        table.string('password_hash', 255).notNullable();
        table.string('full_name', 128).notNullable();
        table.string('phone', 32);
        table.enum('status', ['ACTIVE', 'INACTIVE', 'LOCKED']).defaultTo('ACTIVE');
        table.enum('role', ['ADMIN', 'MANAGER', 'OPERATOR', 'FINANCE', 'SOURCING', 'LOGISTICS', 'ANALYST']).notNullable();
        table.boolean('is_superadmin').defaultTo(false);
        table.string('last_login_by', 36);
        table.datetime('last_login_at');
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.foreign('tenant_id').references('id').inTable('cf_tenant').onDelete('CASCADE');
      });
      logger.info('[DatabaseSchema] Table cf_user created');
    }
  }

  // 角色表
  private static async initRoleTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_role');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_role table...');
      await db.schema.createTable('cf_role', (table) => {
        table.string('id', 36).primary();
        table.string('name', 64).notNullable().unique();
        table.string('description', 255).notNullable();
        table.enum('type', ['SYSTEM', 'CUSTOM']).defaultTo('CUSTOM');
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
      });
      logger.info('[DatabaseSchema] Table cf_role created');
    }
  }

  // 权限表
  private static async initPermissionTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_permission');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_permission table...');
      await db.schema.createTable('cf_permission', (table) => {
        table.string('id', 36).primary();
        table.string('name', 64).notNullable().unique();
        table.string('code', 64).notNullable().unique();
        table.string('description', 255).notNullable();
        table.string('module', 64).notNullable();
        table.enum('action', ['READ', 'WRITE', 'DELETE', 'EXECUTE']).notNullable();
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.index('module');
        table.index('action');
      });
      logger.info('[DatabaseSchema] Table cf_permission created');
    }
  }

  // 角色权限关联表
  private static async initRolePermissionTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_role_permission');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_role_permission table...');
      await db.schema.createTable('cf_role_permission', (table) => {
        table.string('id', 36).primary();
        table.string('role_id', 36).notNullable().index();
        table.string('permission_id', 36).notNullable().index();
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.unique(['role_id', 'permission_id']);
        table.foreign('role_id').references('id').inTable('cf_role').onDelete('CASCADE');
        table.foreign('permission_id').references('id').inTable('cf_permission').onDelete('CASCADE');
      });
      logger.info('[DatabaseSchema] Table cf_role_permission created');
    }
  }

  // 用户角色关联表
  private static async initUserRoleTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_user_role');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_user_role table...');
      await db.schema.createTable('cf_user_role', (table) => {
        table.string('id', 36).primary();
        table.string('user_id', 36).notNullable().index();
        table.string('role_id', 36).notNullable().index();
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.unique(['user_id', 'role_id']);
        table.foreign('user_id').references('id').inTable('cf_user').onDelete('CASCADE');
        table.foreign('role_id').references('id').inTable('cf_role').onDelete('CASCADE');
      });
      logger.info('[DatabaseSchema] Table cf_user_role created');
    }
  }

  // 商品表
  private static async initProductTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_product');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_product table...');
      await db.schema.createTable('cf_product', (table) => {
        table.string('id', 36).primary();
        table.string('tenant_id', 36).notNullable().index();
        table.string('shop_id', 36).notNullable().index();
        table.string('platform', 32).notNullable();
        table.string('product_id', 128).notNullable();
        table.string('title', 255).notNullable();
        table.text('description').notNullable();
        table.string('category', 128).notNullable();
        table.string('brand', 128).notNullable();
        table.decimal('price', 10, 2).notNullable();
        table.decimal('cost_price', 10, 2).notNullable();
        table.integer('stock').notNullable().defaultTo(0);
        table.string('sku', 64).notNullable();
        table.json('attributes').notNullable();
        table.json('images').notNullable();
        table.enum('status', ['ACTIVE', 'INACTIVE', 'OUT_OF_STOCK', 'DELETED']).defaultTo('ACTIVE');
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.unique(['platform', 'product_id']);
        table.foreign('tenant_id').references('id').inTable('cf_tenant').onDelete('CASCADE');
        table.foreign('shop_id').references('id').inTable('cf_shop').onDelete('CASCADE');
      });
      logger.info('[DatabaseSchema] Table cf_product created');
    }
  }

  // 订单表
  private static async initOrderTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_order');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_order table...');
      await db.schema.createTable('cf_order', (table) => {
        table.string('id', 36).primary();
        table.string('tenant_id', 36).notNullable().index();
        table.string('shop_id', 36).notNullable().index();
        table.string('platform', 32).notNullable();
        table.string('platform_order_id', 128).notNullable();
        table.string('customer_id', 36).notNullable();
        table.string('customer_name', 128).notNullable();
        table.string('customer_email', 128).notNullable();
        table.string('customer_phone', 32).notNullable();
        table.string('shipping_address', 255).notNullable();
        table.string('billing_address', 255).notNullable();
        table.decimal('subtotal', 10, 2).notNullable();
        table.decimal('shipping_fee', 10, 2).notNullable();
        table.decimal('tax', 10, 2).notNullable();
        table.decimal('total', 10, 2).notNullable();
        table.string('currency', 3).notNullable();
        table.enum('status', ['PENDING', 'PAID', 'SHIPPED', 'DELIVERED', 'CANCELLED', 'REFUNDED']).defaultTo('PENDING');
        table.enum('payment_method', ['CREDIT_CARD', 'PAYPAL', 'BANK_TRANSFER', 'CASH']).notNullable();
        table.string('tracking_number', 128);
        table.string('carrier', 128);
        table.datetime('estimated_delivery');
        table.datetime('actual_delivery');
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.unique(['platform', 'platform_order_id']);
        table.foreign('tenant_id').references('id').inTable('cf_tenant').onDelete('CASCADE');
        table.foreign('shop_id').references('id').inTable('cf_shop').onDelete('CASCADE');
      });
      logger.info('[DatabaseSchema] Table cf_order created');
    }
  }

  // 订单明细表
  private static async initOrderItemTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_order_item');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_order_item table...');
      await db.schema.createTable('cf_order_item', (table) => {
        table.string('id', 36).primary();
        table.string('order_id', 36).notNullable().index();
        table.string('product_id', 36).notNullable().index();
        table.string('product_sku', 64).notNullable();
        table.string('product_name', 255).notNullable();
        table.integer('quantity').notNullable();
        table.decimal('unit_price', 10, 2).notNullable();
        table.decimal('total_price', 10, 2).notNullable();
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.foreign('order_id').references('id').inTable('cf_order').onDelete('CASCADE');
        table.foreign('product_id').references('id').inTable('cf_product').onDelete('SET NULL');
      });
      logger.info('[DatabaseSchema] Table cf_order_item created');
    }
  }

  // 广告表
  private static async initAdvertisementTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_advertisement');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_advertisement table...');
      await db.schema.createTable('cf_advertisement', (table) => {
        table.string('id', 36).primary();
        table.string('tenant_id', 36).notNullable().index();
        table.string('shop_id', 36).notNullable().index();
        table.string('name', 128).notNullable();
        table.string('campaign_id', 36).notNullable();
        table.string('ad_group_id', 36).notNullable();
        table.string('product_id', 36).notNullable().index();
        table.string('platform', 32).notNullable();
        table.decimal('budget', 10, 2).notNullable();
        table.decimal('bid', 10, 2).notNullable();
        table.enum('status', ['ACTIVE', 'PAUSED', 'DELETED']).defaultTo('ACTIVE');
        table.enum('ad_type', ['SEARCH', 'DISPLAY', 'SOCIAL', 'VIDEO']).notNullable();
        table.datetime('start_date').notNullable();
        table.datetime('end_date');
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.foreign('tenant_id').references('id').inTable('cf_tenant').onDelete('CASCADE');
        table.foreign('shop_id').references('id').inTable('cf_shop').onDelete('CASCADE');
        table.foreign('product_id').references('id').inTable('cf_product').onDelete('SET NULL');
      });
      logger.info('[DatabaseSchema] Table cf_advertisement created');
    }
  }

  // 广告指标表
  private static async initAdMetricsTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_ad_metrics');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_ad_metrics table...');
      await db.schema.createTable('cf_ad_metrics', (table) => {
        table.string('id', 36).primary();
        table.string('ad_id', 36).notNullable().index();
        table.date('date').notNullable();
        table.integer('impressions').notNullable().defaultTo(0);
        table.integer('clicks').notNullable().defaultTo(0);
        table.integer('conversions').notNullable().defaultTo(0);
        table.decimal('spend', 10, 2).notNullable().defaultTo(0);
        table.decimal('revenue', 10, 2).notNullable().defaultTo(0);
        table.decimal('ctr', 5, 2).notNullable().defaultTo(0);
        table.decimal('cpc', 10, 2).notNullable().defaultTo(0);
        table.decimal('cpa', 10, 2).notNullable().defaultTo(0);
        table.decimal('roas', 5, 2).notNullable().defaultTo(0);
        table.decimal('acos', 5, 2).notNullable().defaultTo(0);
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.unique(['ad_id', 'date']);
        table.foreign('ad_id').references('id').inTable('cf_advertisement').onDelete('CASCADE');
      });
      logger.info('[DatabaseSchema] Table cf_ad_metrics created');
    }
  }

  // 证书表
  private static async initCertificateTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_certificate');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_certificate table...');
      await db.schema.createTable('cf_certificate', (table) => {
        table.string('id', 36).primary();
        table.string('tenant_id', 36).notNullable().index();
        table.string('shop_id', 36).notNullable().index();
        table.string('certificate_name', 255).notNullable();
        table.enum('certificate_type', [
          'CE', 'FCC', 'ROHS', 'ISO9001', 'ISO14001',
          'FDA', 'UL', 'CCC', 'EXPORT_LICENSE', 'ORIGIN', 'OTHER'
        ]).notNullable();
        table.string('issuing_authority', 255).notNullable();
        table.string('certificate_number', 128).notNullable();
        table.date('issue_date').notNullable();
        table.date('expiry_date').notNullable();
        table.string('file_path', 255).notNullable();
        table.string('file_hash', 64).notNullable();
        table.enum('status', ['VALID', 'EXPIRED', 'PENDING', 'REVOKED']).defaultTo('VALID');
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.foreign('tenant_id').references('id').inTable('cf_tenant').onDelete('CASCADE');
        table.foreign('shop_id').references('id').inTable('cf_shop').onDelete('CASCADE');
      });
      logger.info('[DatabaseSchema] Table cf_certificate created');
    }
  }

  // 合规规则表
  private static async initComplianceRuleTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_compliance_rule');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_compliance_rule table...');
      await db.schema.createTable('cf_compliance_rule', (table) => {
        table.string('id', 36).primary();
        table.string('platform', 32).notNullable();
        table.string('product_category', 128).notNullable();
        table.json('required_certificates').notNullable();
        table.json('prohibited_items').notNullable();
        table.json('restrictions').notNullable();
        table.string('description', 255).notNullable();
        table.enum('status', ['ACTIVE', 'INACTIVE']).defaultTo('ACTIVE');
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.index('platform');
        table.index('product_category');
      });
      logger.info('[DatabaseSchema] Table cf_compliance_rule created');
    }
  }

  // 审计日志表
  private static async initAuditLogTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_audit_log');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_audit_log table...');
      await db.schema.createTable('cf_audit_log', (table) => {
        table.string('id', 36).primary();
        table.string('tenant_id', 36).notNullable().index();
        table.string('user_id', 36).notNullable().index();
        table.string('action', 128).notNullable();
        table.string('resource_type', 64).notNullable();
        table.string('resource_id', 36).notNullable();
        table.json('old_value').nullable();
        table.json('new_value').nullable();
        table.string('ip_address', 32).notNullable();
        table.string('user_agent', 255).notNullable();
        table.string('trace_id', 64).notNullable();
        table.enum('business_type', ['TOC', 'TOB']).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.index('action');
        table.index('resource_type');
        table.index('created_at');
      });
      logger.info('[DatabaseSchema] Table cf_audit_log created');
    }
  }

  // 安全相关表
  private static async initSecurityTables(): Promise<void> {
    // 安全测试表
    const hasSecurityTestTable = await db.schema.hasTable('cf_security_test');
    if (!hasSecurityTestTable) {
      logger.info('[DatabaseSchema] Creating cf_security_test table...');
      await db.schema.createTable('cf_security_test', (table) => {
        table.string('id', 64).primary();
        table.string('target_url', 255).notNullable();
        table.datetime('start_time').notNullable();
        table.datetime('end_time').notNullable();
        table.integer('duration').notNullable();
        table.integer('total_tests').notNullable();
        table.integer('passed_tests').notNullable();
        table.integer('failed_tests').notNullable();
        table.decimal('risk_score', 5, 2).notNullable();
        table.text('summary').notNullable();
        table.json('vulnerabilities').notNullable();
        table.json('recommendations').notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.index('created_at');
      });
      logger.info('[DatabaseSchema] Table cf_security_test created');
    }

    // 安全扫描表
    const hasSecurityScanTable = await db.schema.hasTable('cf_security_scan');
    if (!hasSecurityScanTable) {
      logger.info('[DatabaseSchema] Creating cf_security_scan table...');
      await db.schema.createTable('cf_security_scan', (table) => {
        table.string('id', 64).primary();
        table.string('project_root', 255).notNullable();
        table.datetime('scan_time').notNullable();
        table.integer('total_dependencies').notNullable();
        table.integer('vulnerable_dependencies').notNullable();
        table.json('severity_counts').notNullable();
        table.decimal('risk_score', 5, 2).notNullable();
        table.text('summary').notNullable();
        table.json('vulnerabilities').notNullable();
        table.json('recommendations').notNullable();
        table.json('license_issues').notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.index('created_at');
      });
      logger.info('[DatabaseSchema] Table cf_security_scan created');
    }
  }

  // 测试相关表
  private static async initTestTables(): Promise<void> {
    // P0检查表
    const hasP0CheckTable = await db.schema.hasTable('cf_p0_check');
    if (!hasP0CheckTable) {
      logger.info('[DatabaseSchema] Creating cf_p0_check table...');
      await db.schema.createTable('cf_p0_check', (table) => {
        table.string('id', 64).primary();
        table.datetime('check_time').notNullable();
        table.integer('total_p0_tasks').notNullable();
        table.integer('completed_p0_tasks').notNullable();
        table.integer('pending_p0_tasks').notNullable();
        table.integer('failed_p0_tasks').notNullable();
        table.boolean('is_ready_for_launch').notNullable();
        table.text('summary').notNullable();
        table.json('blocking_issues').notNullable();
        table.json('recommendations').notNullable();
        table.json('tasks').notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.index('created_at');
      });
      logger.info('[DatabaseSchema] Table cf_p0_check created');
    }

    // 回归测试表
    const hasRegressionTestTable = await db.schema.hasTable('cf_regression_test');
    if (!hasRegressionTestTable) {
      logger.info('[DatabaseSchema] Creating cf_regression_test table...');
      await db.schema.createTable('cf_regression_test', (table) => {
        table.string('id', 64).primary();
        table.string('test_suite', 128).notNullable();
        table.datetime('start_time').notNullable();
        table.datetime('end_time').notNullable();
        table.integer('duration').notNullable();
        table.integer('total_tests').notNullable();
        table.integer('passed_tests').notNullable();
        table.integer('failed_tests').notNullable();
        table.integer('skipped_tests').notNullable();
        table.boolean('success').notNullable();
        table.text('summary').notNullable();
        table.json('recommendations').notNullable();
        table.json('results').notNullable();
        table.string('environment', 32).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.index('created_at');
      });
      logger.info('[DatabaseSchema] Table cf_regression_test created');
    }
  }

  private static async initMerchantMetricsTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_merchant_metrics');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_merchant_metrics table...');
      await db.schema.createTable('cf_merchant_metrics', (table) => {
        table.string('id', 36).primary();
        table.string('tenant_id', 36).notNullable();
        table.string('shop_id', 36).notNullable();
        table.decimal('total_revenue', 12, 2).defaultTo(0);
        table.decimal('total_cost', 12, 2).defaultTo(0);
        table.decimal('total_profit', 12, 2).defaultTo(0);
        table.decimal('roi', 8, 4).defaultTo(0);
        table.decimal('growth_rate', 8, 4).defaultTo(0);
        table.integer('order_count').defaultTo(0);
        table.integer('product_count').defaultTo(0);
        table.decimal('avg_order_value', 10, 2).defaultTo(0);
        table.decimal('return_rate', 5, 4).defaultTo(0);
        table.string('top_strategy', 128);
        table.string('top_platform', 32);
        table.enum('tier', ['BRONZE', 'SILVER', 'GOLD', 'PLATINUM', 'DIAMOND']).defaultTo('BRONZE');
        table.boolean('is_verified').defaultTo(false);
        table.datetime('metrics_date').notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.index(['tenant_id', 'metrics_date']);
        table.index('total_profit');
        table.index('roi');
        table.index('growth_rate');
        table.foreign('tenant_id').references('id').inTable('cf_tenant').onDelete('CASCADE');
        table.foreign('shop_id').references('id').inTable('cf_shop').onDelete('CASCADE');
      });
      logger.info('[DatabaseSchema] Table cf_merchant_metrics created');
    }
  }

  private static async initLeaderboardSnapshotTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_leaderboard_snapshot');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_leaderboard_snapshot table...');
      await db.schema.createTable('cf_leaderboard_snapshot', (table) => {
        table.string('id', 36).primary();
        table.enum('leaderboard_type', ['REVENUE', 'ROI', 'GROWTH']).notNullable();
        table.enum('period', ['DAILY', 'WEEKLY', 'MONTHLY', 'ALL_TIME']).notNullable();
        table.json('rankings').notNullable();
        table.integer('total_merchants').notNullable();
        table.decimal('total_revenue', 14, 2).defaultTo(0);
        table.datetime('snapshot_date').notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.index(['leaderboard_type', 'period', 'snapshot_date']);
        table.index('snapshot_date');
      });
      logger.info('[DatabaseSchema] Table cf_leaderboard_snapshot created');
    }
  }

  private static async initStrategiesTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_strategies');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_strategies table...');
      await db.schema.createTable('cf_strategies', (table) => {
        table.string('id', 36).primary();
        table.string('name', 128).notNullable();
        table.text('description').notNullable();
        table.enum('category', ['PRICING', 'ADVERTISING', 'PRODUCT_SELECTION', 'INVENTORY', 'LOGISTICS', 'MARKETING']).notNullable();
        table.enum('risk_level', ['LOW', 'MEDIUM', 'HIGH']).defaultTo('MEDIUM');
        table.decimal('price', 10, 2).defaultTo(0);
        table.enum('billing_type', ['FREE', 'ONE_TIME', 'SUBSCRIPTION', 'USAGE_BASED']).defaultTo('FREE');
        table.json('parameters').notNullable();
        table.json('default_config').notNullable();
        table.decimal('avg_roi', 8, 4).defaultTo(0);
        table.integer('usage_count').defaultTo(0);
        table.integer('success_rate').defaultTo(0);
        table.json('tags').notNullable();
        table.boolean('is_active').defaultTo(true);
        table.boolean('is_featured').defaultTo(false);
        table.string('created_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.index('category');
        table.index('is_active');
        table.index('is_featured');
        table.index('avg_roi');
      });
      logger.info('[DatabaseSchema] Table cf_strategies created');
    }
  }

  private static async initMerchantStrategiesTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_merchant_strategies');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_merchant_strategies table...');
      await db.schema.createTable('cf_merchant_strategies', (table) => {
        table.string('id', 36).primary();
        table.string('tenant_id', 36).notNullable();
        table.string('strategy_id', 36).notNullable();
        table.enum('status', ['ACTIVE', 'PAUSED', 'COMPLETED', 'FAILED']).defaultTo('ACTIVE');
        table.json('config').notNullable();
        table.json('results').notNullable();
        table.decimal('roi_achieved', 8, 4).defaultTo(0);
        table.decimal('revenue_generated', 12, 2).defaultTo(0);
        table.datetime('activated_at').notNullable();
        table.datetime('completed_at');
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.index(['tenant_id', 'status']);
        table.index('strategy_id');
        table.foreign('tenant_id').references('id').inTable('cf_tenant').onDelete('CASCADE');
        table.foreign('strategy_id').references('id').inTable('cf_strategies').onDelete('CASCADE');
      });
      logger.info('[DatabaseSchema] Table cf_merchant_strategies created');
    }
  }

  private static async initAutopilotSessionsTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_autopilot_sessions');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_autopilot_sessions table...');
      await db.schema.createTable('cf_autopilot_sessions', (table) => {
        table.string('id', 36).primary();
        table.string('tenant_id', 36).notNullable();
        table.string('shop_id', 36).notNullable();
        table.enum('status', ['IDLE', 'RUNNING', 'PAUSED', 'STOPPED', 'ERROR']).defaultTo('IDLE');
        table.enum('mode', ['FULL_AUTO', 'SEMI_AUTO', 'MANUAL']).defaultTo('SEMI_AUTO');
        table.json('config').notNullable();
        table.json('enabled_features').notNullable();
        table.decimal('total_revenue', 12, 2).defaultTo(0);
        table.decimal('total_orders', 10).defaultTo(0);
        table.decimal('total_profit', 12, 2).defaultTo(0);
        table.integer('tasks_completed').defaultTo(0);
        table.integer('tasks_failed').defaultTo(0);
        table.datetime('started_at');
        table.datetime('stopped_at');
        table.datetime('last_activity_at');
        table.string('error_message', 512);
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.index(['tenant_id', 'shop_id']);
        table.index('status');
        table.foreign('tenant_id').references('id').inTable('cf_tenant').onDelete('CASCADE');
        table.foreign('shop_id').references('id').inTable('cf_shop').onDelete('CASCADE');
      });
      logger.info('[DatabaseSchema] Table cf_autopilot_sessions created');
    }
  }

  private static async initAutopilotLogsTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_autopilot_logs');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_autopilot_logs table...');
      await db.schema.createTable('cf_autopilot_logs', (table) => {
        table.string('id', 36).primary();
        table.string('session_id', 36).notNullable();
        table.string('tenant_id', 36).notNullable();
        table.enum('log_type', ['TASK', 'DECISION', 'ERROR', 'WARNING', 'INFO']).notNullable();
        table.string('task_type', 64);
        table.enum('task_status', ['PENDING', 'RUNNING', 'COMPLETED', 'FAILED']).defaultTo('PENDING');
        table.text('description').notNullable();
        table.json('input_data');
        table.json('output_data');
        table.json('error_details');
        table.integer('duration_ms').defaultTo(0);
        table.boolean('is_auto_executed').defaultTo(false);
        table.string('trace_id', 64);
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.index(['session_id', 'created_at']);
        table.index(['tenant_id', 'log_type']);
        table.index('task_type');
        table.foreign('session_id').references('id').inTable('cf_autopilot_sessions').onDelete('CASCADE');
        table.foreign('tenant_id').references('id').inTable('cf_tenant').onDelete('CASCADE');
      });
      logger.info('[DatabaseSchema] Table cf_autopilot_logs created');
    }
  }

  private static async initPriceComparisonsTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_price_comparisons');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_price_comparisons table...');
      await db.schema.createTable('cf_price_comparisons', (table) => {
        table.string('id', 36).primary();
        table.string('tenant_id', 36).notNullable();
        table.string('product_id', 36).notNullable();
        table.string('product_name', 255).notNullable();
        table.string('source_platform', 50).notNullable();
        table.decimal('source_price', 12, 2).notNullable();
        table.string('source_currency', 10).notNullable();
        table.string('target_platform', 50).notNullable();
        table.decimal('target_price', 12, 2).notNullable();
        table.string('target_currency', 10).notNullable();
        table.decimal('price_difference', 12, 2).notNullable();
        table.decimal('price_difference_percent', 8, 4).notNullable();
        table.decimal('exchange_rate', 10, 4).notNullable();
        table.json('profit_snapshot');
        table.enum('risk_level', ['LOW', 'MEDIUM', 'HIGH', 'BLOCK']).defaultTo('LOW');
        table.integer('opportunity_score').defaultTo(0);
        table.enum('status', ['ACTIVE', 'EXPIRED', 'EXECUTED']).defaultTo('ACTIVE');
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.index(['tenant_id', 'product_id']);
        table.index(['target_platform', 'status']);
        table.index('opportunity_score');
        table.foreign('tenant_id').references('id').inTable('cf_tenant').onDelete('CASCADE');
      });
      logger.info('[DatabaseSchema] Table cf_price_comparisons created');
    }
  }

  private static async initArbitrageOpportunitiesTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_arbitrage_opportunities');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_arbitrage_opportunities table...');
      await db.schema.createTable('cf_arbitrage_opportunities', (table) => {
        table.string('id', 36).primary();
        table.string('tenant_id', 36).notNullable();
        table.string('product_id', 36).notNullable();
        table.string('product_name', 255).notNullable();
        table.string('source_platform', 50).notNullable();
        table.string('source_url', 512);
        table.decimal('source_price', 12, 2).notNullable();
        table.string('source_currency', 10).notNullable();
        table.string('target_platform', 50).notNullable();
        table.decimal('target_price', 12, 2).notNullable();
        table.string('target_currency', 10).notNullable();
        table.json('profit_snapshot').notNullable();
        table.enum('risk_level', ['LOW', 'MEDIUM', 'HIGH', 'BLOCK']).defaultTo('LOW');
        table.integer('opportunity_score').defaultTo(0);
        table.enum('status', ['PENDING', 'APPROVED', 'REJECTED', 'EXECUTING', 'EXECUTED', 'FAILED']).defaultTo('PENDING');
        table.enum('execution_mode', ['AUTO', 'MANUAL']).defaultTo('MANUAL');
        table.datetime('executed_at');
        table.string('error_message', 512);
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.index(['tenant_id', 'status']);
        table.index(['target_platform', 'risk_level']);
        table.index('opportunity_score');
        table.foreign('tenant_id').references('id').inTable('cf_tenant').onDelete('CASCADE');
      });
      logger.info('[DatabaseSchema] Table cf_arbitrage_opportunities created');
    }
  }

  private static async initArbitrageExecutionsTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_arbitrage_executions');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_arbitrage_executions table...');
      await db.schema.createTable('cf_arbitrage_executions', (table) => {
        table.string('id', 36).primary();
        table.string('opportunity_id', 36).notNullable();
        table.string('tenant_id', 36).notNullable();
        table.enum('status', ['STARTED', 'PURCHASED', 'LISTED', 'SOLD', 'COMPLETED', 'FAILED']).defaultTo('STARTED');
        table.string('purchase_order_id', 36);
        table.string('listing_id', 36);
        table.string('sale_order_id', 36);
        table.decimal('actual_purchase_price', 12, 2);
        table.decimal('actual_sale_price', 12, 2);
        table.decimal('actual_profit', 12, 2);
        table.text('notes');
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.index(['opportunity_id', 'status']);
        table.index('tenant_id');
        table.foreign('opportunity_id').references('id').inTable('cf_arbitrage_opportunities').onDelete('CASCADE');
        table.foreign('tenant_id').references('id').inTable('cf_tenant').onDelete('CASCADE');
      });
      logger.info('[DatabaseSchema] Table cf_arbitrage_executions created');
    }
  }

  // 货币相关表
  private static async initCurrencyTables(): Promise<void> {
    await this.initCurrencyTable();
    await this.initExchangeRateTable();
    await this.initExchangeRateHistoryTable();
  }

  // 货币表
  private static async initCurrencyTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_currency');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_currency table...');
      await db.schema.createTable('cf_currency', (table) => {
        table.string('id', 36).primary();
        table.string('code', 3).notNullable().unique();
        table.string('name', 64).notNullable();
        table.string('symbol', 10).notNullable();
        table.integer('decimal_places').notNullable().defaultTo(2);
        table.string('format', 64).notNullable();
        table.boolean('is_active').defaultTo(true);
        table.boolean('is_default').defaultTo(false);
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.index('code');
        table.index('is_active');
        table.index('is_default');
      });
      logger.info('[DatabaseSchema] Table cf_currency created');
    }
  }

  // 汇率表
  private static async initExchangeRateTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_exchange_rate');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_exchange_rate table...');
      await db.schema.createTable('cf_exchange_rate', (table) => {
        table.string('id', 36).primary();
        table.string('from_currency', 3).notNullable();
        table.string('to_currency', 3).notNullable();
        table.decimal('rate', 16, 6).notNullable();
        table.decimal('inverse_rate', 16, 6).notNullable();
        table.datetime('last_updated').notNullable().defaultTo(db.fn.now());
        table.string('source', 64).notNullable();
        table.string('created_by', 36).notNullable();
        table.string('updated_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.datetime('updated_at').notNullable().defaultTo(db.fn.now());
        table.unique(['from_currency', 'to_currency']);
        table.index('from_currency');
        table.index('to_currency');
        table.index('last_updated');
      });
      logger.info('[DatabaseSchema] Table cf_exchange_rate created');
    }
  }

  // 汇率历史表
  private static async initExchangeRateHistoryTable(): Promise<void> {
    const hasTable = await db.schema.hasTable('cf_exchange_rate_history');
    if (!hasTable) {
      logger.info('[DatabaseSchema] Creating cf_exchange_rate_history table...');
      await db.schema.createTable('cf_exchange_rate_history', (table) => {
        table.string('id', 36).primary();
        table.string('from_currency', 3).notNullable();
        table.string('to_currency', 3).notNullable();
        table.decimal('rate', 16, 6).notNullable();
        table.date('date').notNullable();
        table.string('source', 64).notNullable();
        table.string('created_by', 36).notNullable();
        table.datetime('created_at').notNullable().defaultTo(db.fn.now());
        table.unique(['from_currency', 'to_currency', 'date']);
        table.index('from_currency');
        table.index('to_currency');
        table.index('date');
      });
      logger.info('[DatabaseSchema] Table cf_exchange_rate_history created');
    }
  }

  static async dropAllTables(): Promise<void> {
    const tables = [
      'cf_exchange_rate_history',
      'cf_exchange_rate',
      'cf_currency',
      'cf_arbitrage_executions',
      'cf_arbitrage_opportunities',
      'cf_price_comparisons',
      'cf_autopilot_logs',
      'cf_autopilot_sessions',
      'cf_merchant_strategies',
      'cf_strategies',
      'cf_leaderboard_snapshot',
      'cf_merchant_metrics',
      'cf_regression_test',
      'cf_p0_check',
      'cf_security_scan',
      'cf_security_test',
      'cf_audit_log',
      'cf_compliance_rule',
      'cf_certificate',
      'cf_ad_metrics',
      'cf_advertisement',
      'cf_order_item',
      'cf_order',
      'cf_product',
      'cf_user_role',
      'cf_role_permission',
      'cf_permission',
      'cf_role',
      'cf_user',
      'cf_shop',
      'cf_tenant'
    ];

    for (const table of tables) {
      const hasTable = await db.schema.hasTable(table);
      if (hasTable) {
        logger.info(`[DatabaseSchema] Dropping table ${table}...`);
        await db.schema.dropTable(table);
        logger.info(`[DatabaseSchema] Table ${table} dropped`);
      }
    }
  }

  static async getTableStatus(): Promise<Array<{ table: string; exists: boolean }>> {
    const tables = [
      'cf_tenant',
      'cf_shop',
      'cf_user',
      'cf_role',
      'cf_permission',
      'cf_role_permission',
      'cf_user_role',
      'cf_product',
      'cf_order',
      'cf_order_item',
      'cf_advertisement',
      'cf_ad_metrics',
      'cf_certificate',
      'cf_compliance_rule',
      'cf_audit_log',
      'cf_security_test',
      'cf_security_scan',
      'cf_p0_check',
      'cf_regression_test',
      'cf_merchant_metrics',
      'cf_leaderboard_snapshot',
      'cf_strategies',
      'cf_merchant_strategies',
      'cf_autopilot_sessions',
      'cf_autopilot_logs',
      'cf_price_comparisons',
      'cf_arbitrage_opportunities',
      'cf_arbitrage_executions',
      'cf_pricing_configs',
      'cf_pricing_decisions',
      'cf_price_history',
      'cf_pricing_ab_tests',
      'cf_competitor_prices',
      'cf_competitor_price_history',
      'cf_price_alerts',
      'cf_competitor_monitor_configs'
    ];

    const status: Array<{ table: string; exists: boolean }> = [];
    for (const table of tables) {
      const exists = await db.schema.hasTable(table);
      status.push({ table, exists });
    }

    return status;
  }

  // 定价相关表
  private static async initPricingTables(): Promise<void> {
    // 定价配置表
    const hasConfigTable = await db.schema.hasTable('cf_pricing_configs');
    if (!hasConfigTable) {
      logger.info('[DatabaseSchema] Creating cf_pricing_configs table...');
      await db.schema.createTable('cf_pricing_configs', (table) => {
        table.string('id', 50).primary();
        table.string('tenant_id', 50).notNullable().index();
        table.string('shop_id', 50).notNullable().index();
        table.string('product_id', 50).notNullable();
        
        table.decimal('base_price', 10, 2).notNullable();
        table.decimal('min_price', 10, 2).notNullable();
        table.decimal('max_price', 10, 2).notNullable();
        table.decimal('cost_price', 10, 2).notNullable();
        
        table.enum('strategy', ['GAME_THEORY', 'COMPETITION', 'DEMAND_BASED', 'COST_PLUS', 'DYNAMIC']).notNullable();
        table.json('strategy_params').notNullable();
        
        table.boolean('auto_adjust').notNullable().defaultTo(false);
        table.enum('adjust_frequency', ['HOURLY', 'DAILY', 'WEEKLY']).notNullable().defaultTo('DAILY');
        table.decimal('max_adjust_percent', 5, 2).notNullable().defaultTo(10);
        table.integer('cooldown_hours').notNullable().defaultTo(24);
        
        table.decimal('min_profit_margin', 5, 2).notNullable().defaultTo(15);
        table.decimal('min_profit_amount', 10, 2).notNullable().defaultTo(0);
        
        table.boolean('enabled').notNullable().defaultTo(true);
        table.timestamp('created_at').notNullable().defaultTo(db.fn.now());
        table.timestamp('updated_at').notNullable().defaultTo(db.fn.now());
        
        table.unique(['shop_id', 'product_id']);
        table.index(['tenant_id', 'enabled']);
      });
      logger.info('[DatabaseSchema] Table cf_pricing_configs created');
    }

    // 定价决策表
    const hasDecisionTable = await db.schema.hasTable('cf_pricing_decisions');
    if (!hasDecisionTable) {
      logger.info('[DatabaseSchema] Creating cf_pricing_decisions table...');
      await db.schema.createTable('cf_pricing_decisions', (table) => {
        table.string('id', 50).primary();
        table.string('tenant_id', 50).notNullable().index();
        table.string('shop_id', 50).notNullable().index();
        table.string('product_id', 50).notNullable().index();
        
        table.decimal('current_price', 10, 2).notNullable();
        table.decimal('suggested_price', 10, 2).notNullable();
        table.decimal('price_change', 10, 2).notNullable();
        table.decimal('change_percent', 5, 2).notNullable();
        table.enum('adjustment_direction', ['INCREASE', 'DECREASE', 'MAINTAIN']).notNullable();
        
        table.enum('strategy_used', ['GAME_THEORY', 'COMPETITION', 'DEMAND_BASED', 'COST_PLUS', 'DYNAMIC']).notNullable();
        table.json('decision_factors').notNullable();
        table.json('predicted_impact').notNullable();
        
        table.enum('status', ['PENDING', 'EXECUTED', 'REJECTED', 'EXPIRED']).notNullable().defaultTo('PENDING');
        
        table.string('reviewed_by', 50).nullable();
        table.timestamp('reviewed_at').nullable();
        table.text('review_notes').nullable();
        
        table.timestamp('executed_at').nullable();
        table.json('execution_result').nullable();
        
        table.timestamp('created_at').notNullable().defaultTo(db.fn.now());
        table.timestamp('expires_at').notNullable();
        
        table.index(['tenant_id', 'status', 'created_at']);
      });
      logger.info('[DatabaseSchema] Table cf_pricing_decisions created');
    }

    // 价格历史表
    const hasHistoryTable = await db.schema.hasTable('cf_price_history');
    if (!hasHistoryTable) {
      logger.info('[DatabaseSchema] Creating cf_price_history table...');
      await db.schema.createTable('cf_price_history', (table) => {
        table.string('id', 50).primary();
        table.string('tenant_id', 50).notNullable().index();
        table.string('shop_id', 50).notNullable().index();
        table.string('product_id', 50).notNullable().index();
        
        table.decimal('old_price', 10, 2).notNullable();
        table.decimal('new_price', 10, 2).notNullable();
        table.string('change_reason', 200).notNullable();
        table.enum('strategy_used', ['GAME_THEORY', 'COMPETITION', 'DEMAND_BASED', 'COST_PLUS', 'DYNAMIC']).notNullable();
        table.json('impact_metrics').nullable();
        
        table.timestamp('created_at').notNullable().defaultTo(db.fn.now());
      });
      logger.info('[DatabaseSchema] Table cf_price_history created');
    }

    // A/B测试表
    const hasABTestTable = await db.schema.hasTable('cf_pricing_ab_tests');
    if (!hasABTestTable) {
      logger.info('[DatabaseSchema] Creating cf_pricing_ab_tests table...');
      await db.schema.createTable('cf_pricing_ab_tests', (table) => {
        table.string('id', 50).primary();
        table.string('tenant_id', 50).notNullable().index();
        table.string('shop_id', 50).notNullable().index();
        table.string('product_id', 50).notNullable().index();
        
        table.string('test_name', 100).notNullable();
        table.string('test_description', 500).notNullable();
        
        table.decimal('control_price', 10, 2).notNullable();
        table.json('test_prices').notNullable();
        
        table.integer('sample_size').notNullable();
        table.integer('duration_days').notNullable();
        
        table.enum('status', ['PENDING', 'RUNNING', 'COMPLETED', 'STOPPED']).notNullable().defaultTo('PENDING');
        
        table.json('results').nullable();
        table.string('winner_variation', 50).nullable();
        table.decimal('confidence_level', 5, 4).nullable();
        
        table.timestamp('started_at').nullable();
        table.timestamp('ended_at').nullable();
        table.timestamp('created_at').notNullable().defaultTo(db.fn.now());
        table.timestamp('updated_at').notNullable().defaultTo(db.fn.now());
        
        table.index(['tenant_id', 'status']);
      });
      logger.info('[DatabaseSchema] Table cf_pricing_ab_tests created');
    }
  }

  // 竞争对手价格相关表
  private static async initCompetitorPriceTables(): Promise<void> {
    // 竞争对手价格表
    const hasPriceTable = await db.schema.hasTable('cf_competitor_prices');
    if (!hasPriceTable) {
      logger.info('[DatabaseSchema] Creating cf_competitor_prices table...');
      await db.schema.createTable('cf_competitor_prices', (table) => {
        table.string('id', 50).primary();
        table.string('tenant_id', 50).notNullable().index();
        table.string('product_id', 50).notNullable().index();
        table.string('competitor_name', 100).notNullable();
        table.string('competitor_url', 500).notNullable();
        table.decimal('price', 10, 2).notNullable();
        table.string('currency', 10).notNullable();
        table.string('shipping_cost', 10).notNullable();
        table.string('stock_status', 50).notNullable();
        table.json('product_attributes').nullable();
        table.timestamp('last_updated').notNullable().defaultTo(db.fn.now());
        table.timestamp('created_at').notNullable().defaultTo(db.fn.now());
        table.index(['product_id', 'competitor_name']);
      });
      logger.info('[DatabaseSchema] Table cf_competitor_prices created');
    }

    // 竞争对手价格历史表
    const hasHistoryTable = await db.schema.hasTable('cf_competitor_price_history');
    if (!hasHistoryTable) {
      logger.info('[DatabaseSchema] Creating cf_competitor_price_history table...');
      await db.schema.createTable('cf_competitor_price_history', (table) => {
        table.string('id', 50).primary();
        table.string('product_id', 50).notNullable().index();
        table.string('competitor_name', 100).notNullable();
        table.decimal('price', 10, 2).notNullable();
        table.string('currency', 10).notNullable();
        table.date('date').notNullable();
        table.timestamp('created_at').notNullable().defaultTo(db.fn.now());
        table.index(['product_id', 'date']);
      });
      logger.info('[DatabaseSchema] Table cf_competitor_price_history created');
    }

    // 价格预警表
    const hasAlertTable = await db.schema.hasTable('cf_price_alerts');
    if (!hasAlertTable) {
      logger.info('[DatabaseSchema] Creating cf_price_alerts table...');
      await db.schema.createTable('cf_price_alerts', (table) => {
        table.string('id', 50).primary();
        table.string('tenant_id', 50).notNullable().index();
        table.string('product_id', 50).notNullable().index();
        table.string('alert_type', 50).notNullable();
        table.string('message', 500).notNullable();
        table.decimal('threshold_price', 10, 2).notNullable();
        table.decimal('current_price', 10, 2).notNullable();
        table.string('competitor_name', 100).nullable();
        table.enum('status', ['ACTIVE', 'RESOLVED', 'IGNORED']).notNullable().defaultTo('ACTIVE');
        table.timestamp('created_at').notNullable().defaultTo(db.fn.now());
        table.timestamp('resolved_at').nullable();
        table.index(['tenant_id', 'status']);
      });
      logger.info('[DatabaseSchema] Table cf_price_alerts created');
    }

    // 竞争对手监控配置表
    const hasConfigTable = await db.schema.hasTable('cf_competitor_monitor_configs');
    if (!hasConfigTable) {
      logger.info('[DatabaseSchema] Creating cf_competitor_monitor_configs table...');
      await db.schema.createTable('cf_competitor_monitor_configs', (table) => {
        table.string('id', 50).primary();
        table.string('tenant_id', 50).notNullable().index();
        table.string('product_id', 50).notNullable().index();
        table.json('competitors').notNullable();
        table.integer('check_interval_minutes').notNullable().defaultTo(60);
        table.boolean('enabled').notNullable().defaultTo(true);
        table.decimal('price_change_threshold', 5, 2).notNullable().defaultTo(5);
        table.timestamp('last_check_at').nullable();
        table.timestamp('created_at').notNullable().defaultTo(db.fn.now());
        table.timestamp('updated_at').notNullable().defaultTo(db.fn.now());
      });
      logger.info('[DatabaseSchema] Table cf_competitor_monitor_configs created');
    }
  }
}
