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

/**
 * [BIZ_INF_107] 数据库索引覆盖率审计 (Index Audit)
 * @description 核心逻辑：扫描数据库表结构并分析其索引覆盖情况。
 * 特别针对 [cf_product] 等高频访问表进行主键、唯一约束与常用字段的索引缺失审计。
 * 联动语义日志中心输出索引覆盖率报告并建议缺失的索引。
 */
export class IndexCoverageService {
  private static readonly AUDIT_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000; // 审计间隔：1周

  /**
   * 初始化审计任务
   */
  static async init() {
    this.runAudit();
    setInterval(() => this.runAudit(), this.AUDIT_INTERVAL_MS);
    logger.info(`[IndexAudit] Service initialized (Interval: 1 week)`);
  }

  /**
   * 执行审计并生成报告
   */
  private static async runAudit() {
    try {
      const report = await this.generateReport();
      await SemanticLogService.logSemantic(report, 'INFO', 'DB_AUDIT');
      logger.info(`[IndexAudit] Audit report generated for cf_product`);
    } catch (err: any) {
      logger.error(`[IndexAudit] Audit failed: ${err.message}`);
    }
  }

  /**
   * 生成索引覆盖率报告
   */
  private static async generateReport(): Promise<string> {
    const table = 'cf_product';
    const indexes = await db.raw(`SHOW INDEX FROM ${table}`);
    const indexRows = indexes[0];

    const columns = await db.raw(`SHOW COLUMNS FROM ${table}`);
    const columnRows = columns[0];

    const indexedColumns = new Set(indexRows.map((row: any) => row.Column_name));
    const allColumns = columnRows.map((row: any) => row.Field);

    const coverageRatio = (indexedColumns.size / allColumns.length) * 100;

    let report = `### 🔍 Index Coverage Audit: \`${table}\`\n\n`;
    report += `**Indexed Columns:** \`${Array.from(indexedColumns).join(', ')}\`\n\n`;
    report += `**Total Columns:** ${allColumns.length} | **Coverage Ratio:** ${coverageRatio.toFixed(2)}%\n\n`;

    // 识别核心字段索引缺失
    const coreFields = ['tenant_id', 'product_id', 'platform', 'status', 'created_at'];
    const missingCoreIndexes = coreFields.filter(field => !indexedColumns.has(field));

    if (missingCoreIndexes.length > 0) {
      report += `**⚠️ Missing Core Field Indexes:**\n`;
      missingCoreIndexes.forEach(field => {
        report += `- \`${field}\` (建议为该字段添加索引以优化高频查询)\n`;
      });
    } else {
      report += `**✅ All core fields are properly indexed.**\n`;
    }

    // 唯一性约束审计
    const uniqueIndexes = indexRows.filter((row: any) => row.Non_unique === 0);
    report += `\n**Unique Constraints:** ${uniqueIndexes.length}\n`;
    uniqueIndexes.forEach((row: any) => {
      report += `- \`${row.Key_name}\` (Column: \`${row.Column_name}\`)\n`;
    });

    return report;
  }
}
