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

/**
 * [CORE_SEC_02] 凭据轮换服务 (Credential Rotation)
 * @description 管理凭据的到期提醒、强制轮换与安全变更
 */
export class CredentialRotationService {
  private static readonly ROTATION_INTERVAL_DAYS = 90;

  /**
   * 检查到期凭据
   */
  static async checkExpiringCredentials(): Promise<any[]> {
    const thresholdDate = new Date();
    thresholdDate.setDate(thresholdDate.getDate() - this.ROTATION_INTERVAL_DAYS);

    const expiring = await db('cf_credential_vault')
      .where('updated_at', '<', thresholdDate)
      .orWhereNotNull('expires_at')
      .andWhere('expires_at', '<', new Date());

    return expiring;
  }

  /**
   * 发起受控轮换 (需审批)
   */
  static async initiateControlledRotation(tenantId: string, credentialId: number, userId: string): Promise<string> {
    logger.info(`[Rotation] Initiating controlled rotation for ${credentialId} by user ${userId}`);

    const approvalId = await ApprovalService.requestApproval({
      tenantId,
      requesterId: userId,
      type: 'CREDENTIAL_RESET',
      resourceId: String(credentialId),
      metadata: { action: 'ROTATE', strategy: 'FORCE_NEXT_LOGIN' }
    });

    return approvalId;
  }

  /**
   * 执行轮换逻辑
   */
  static async performRotation(
    context: { tenantId: string; userId: string; traceId: string },
    credentialId: number, 
    newPassword: string
  ): Promise<void> {
    logger.info(`[Rotation] Executing rotation for ${credentialId}`);
    await VaultService.rotateCredential(context, credentialId, newPassword);
  }
}
