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();
    
    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');
    }
  }

  static async dropAllTables(): Promise<void> {
    const tables = [
      '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'
    ];

    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;
  }
}
