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

export interface SecurityProfile {
  tenantId: string;
  riskScore: number; // 0-100
  threatLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  anomaliesDetected: number;
  lastAuditAt: Date;
  topRiskFactors: string[];
}

/**
 * [BIZ_AUDIT_03] 跨租户安全审计与风险画像 (Security Profiling API)
 * @description 核心逻辑：基于用户行为、API 调用频率、地理位置偏移等维度生成租户安全风险画像。
 */
export class SecurityProfilingService {
  private static readonly PROFILES_TABLE = 'cf_security_profiles';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.PROFILES_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.PROFILES_TABLE} table...`);
      await db.schema.createTable(this.PROFILES_TABLE, (table) => {
        table.string('tenantId', 64).primary();
        table.float('riskScore').defaultTo(0);
        table.string('threatLevel', 20).defaultTo('LOW');
        table.integer('anomaliesDetected').defaultTo(0);
        table.timestamp('lastAuditAt');
        table.json('topRiskFactors');
        table.timestamps(true, true);
      });
    }
  }

  /**
   * 生成/更新租户风险画像
   */
  static async generateProfile(tenantId: string): Promise<SecurityProfile> {
    logger.info(`[SecurityProfiling] Analyzing tenant ${tenantId}`);

    try {
      // 1. 获取最近的审计日志 (Mock 逻辑)
      // 实际应从 cf_audit_logs 或专门的遥测表中分析行为
      const auditSummary = {
        unusualLoginAttempts: 2,
        apiRateLimitHits: 15,
        geoIpMismatch: false,
        sensitiveActionCount: 5
      };

      // 2. 计算风险评分 (0-100)
      let riskScore = 0;
      const factors: string[] = [];

      if (auditSummary.unusualLoginAttempts > 5) {
        riskScore += 30;
        factors.push('HIGH_UNUSUAL_LOGIN_ATTEMPTS');
      }
      if (auditSummary.apiRateLimitHits > 10) {
        riskScore += 20;
        factors.push('API_RATE_LIMIT_FREQUENTLY_HIT');
      }
      if (auditSummary.sensitiveActionCount > 10) {
        riskScore += 15;
        factors.push('ABNORMAL_SENSITIVE_ACTIONS');
      }

      riskScore = Math.min(riskScore, 100);

      // 3. 确定威胁等级
      let threatLevel: SecurityProfile['threatLevel'] = 'LOW';
      if (riskScore > 75) threatLevel = 'CRITICAL';
      else if (riskScore > 50) threatLevel = 'HIGH';
      else if (riskScore > 25) threatLevel = 'MEDIUM';

      const profile: SecurityProfile = {
        tenantId,
        riskScore,
        threatLevel,
        anomaliesDetected: factors.length,
        lastAuditAt: new Date(),
        topRiskFactors: factors
      };

      // 4. 保存/更新画像
      await db(this.PROFILES_TABLE)
        .insert({
          tenantId,
          riskScore,
          threatLevel,
          anomaliesDetected: factors.length,
          lastAuditAt: new Date(),
          topRiskFactors: JSON.stringify(factors),
          created_at: new Date(),
          updated_at: new Date()
        })
        .onConflict(['tenantId'])
        .merge();

      return profile;
    } catch (err: any) {
      logger.error(`[SecurityProfiling] Failed for tenant ${tenantId}: ${err.message}`);
      throw err;
    }
  }

  /**
   * 获取租户风险画像
   */
  static async getProfile(tenantId: string): Promise<SecurityProfile | null> {
    return db(this.PROFILES_TABLE).where({ tenantId }).first();
  }
}
