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

/**
 * [BIZ_KER_122] 多租户权限泄露自动探测 (Auth Leak)
 * @description 核心逻辑：扫描系统中各角色的权限配置。
 * 识别不合理的越权配置，如：OPERATOR 角色意外拥有 ADMIN 或 FINANCE 敏感权限。
 * 自动识别跨租户的数据访问风险点，并生成权限泄露审计报告。
 * 遵循 Autocomplete-First (V31.5) 规范。
 */
export class PermissionAuditService {
  private static readonly SENSITIVE_PERMISSIONS = [
    'admin:*', 'finance:*', 'user:delete', 'system:config'
  ];

  /**
   * 初始化权限扫描
   */
  static async init() {
    logger.info(`[AuthLeakMonitor] Initializing permission leakage audit...`);
    this.runAudit();
    setInterval(() => this.runAudit(), 86400000); // 每日审计一次
  }

  /**
   * 执行权限泄露扫描
   * @private
   */
  private static async runAudit() {
    try {
      // 1. 获取所有非 ADMIN 角色及其关联权限
      const rolesWithPermissions = await db('cf_roles')
        .join('cf_role_permissions', 'cf_roles.id', '=', 'cf_role_permissions.role_id')
        .select('cf_roles.name as role_name', 'cf_role_permissions.permission_key', 'cf_roles.tenant_id')
        .whereNot('cf_roles.name', 'ADMIN');

      const leaks: string[] = [];

      // 2. 识别敏感权限泄露
      for (const entry of rolesWithPermissions) {
        if (this.isSensitive(entry.permission_key)) {
          leaks.push(`⚠️ Role \`${entry.role_name}\` (Tenant: ${entry.tenant_id}) 拥有敏感权限: \`${entry.permission_key}\``);
        }
      }

      // 3. 识别跨租户数据访问风险 (模拟检测逻辑)
      const tenantIsolationIssues = await this.checkTenantIsolation();
      leaks.push(...tenantIsolationIssues);

      const report = this.generateMarkdownReport(leaks);
      await SemanticLogService.logSemantic(report, leaks.length > 0 ? 'ERROR' : 'INFO', 'AUTH_AUDIT');

    } catch (err: any) {
      logger.error(`[AuthLeakMonitor] Audit failed: ${err.message}`);
    }
  }

  /**
   * 判断权限是否属于敏感范畴
   * @private
   */
  private static isSensitive(perm: string): boolean {
    return this.SENSITIVE_PERMISSIONS.some(p => perm.includes(p.replace('*', '')));
  }

  /**
   * 模拟检测租户隔离风险点
   * @private
   */
  private static async checkTenantIsolation(): Promise<string[]> {
    // 实际场景应执行 SQL 扫描，检查是否存在跨租户 JOIN 而无 WHERE tenant_id 的逻辑
    return [];
  }

  /**
   * 生成 Markdown 审计报告
   * @private
   */
  private static generateMarkdownReport(leaks: string[]): string {
    return `### 🛡️ Permission Leakage & Auth Audit\n\n` +
           `**Status:** ${leaks.length > 0 ? '🚨 Vulnerabilities Found' : '✅ Compliant'}\n\n` +
           `**Audit Findings:**\n` +
           (leaks.length > 0 ? leaks.map(l => `- ${l}`).join('\n') : '- No sensitive permission leaks detected.') +
           (leaks.length > 0 ? `\n\n**Recommendation:** 请立即回收不合理的敏感权限，并根据 RBAC 规范重新审计角色权限边界。` : '');
  }
}
