import * as crypto from 'crypto';
import { logger } from '../utils/logger';

/**
 * [CORE_SEC_06] 隐私计算 TEE (Trusted Execution Environment) 模拟服务
 * @description 在模拟的受信任执行环境中进行敏感业务计算（如利润率、私密财务数据），防止内存嗅探
 */
export class TEEComputeService {
  private static readonly TEE_KEY = crypto.randomBytes(32); // 模拟 TEE 内部生成的硬件密钥

  /**
   * 执行受保护的计算
   * @param encryptedInput 加密输入数据
   * @param computeLogic 计算逻辑标识
   */
  static async secureCompute(encryptedInput: string, iv: string, tag: string, computeLogic: 'MARGIN' | 'TAX' | 'RECON'): Promise<string> {
    logger.info(`[TEE] Initiating secure compute for: ${computeLogic}`);

    try {
      // 1. 在 TEE 内部解密
      const decipher = crypto.createDecipheriv('aes-256-gcm', this.TEE_KEY, Buffer.from(iv, 'base64'));
      decipher.setAuthTag(Buffer.from(tag, 'base64'));
      let decrypted = decipher.update(encryptedInput, 'hex', 'utf8');
      decrypted += decipher.final('utf8');
      
      const rawData = JSON.parse(decrypted);
      let result: any;

      // 2. 执行受保护的业务逻辑 (模拟)
      switch (computeLogic) {
        case 'MARGIN':
          // 利润率计算：(售价 - 采购价 - 运费 - 平台费) / 售价
          const { price, cost, shipping, platformFee } = rawData;
          const netProfit = price - cost - shipping - platformFee;
          result = { netProfit, margin: netProfit / price };
          break;
        case 'TAX':
          // 模拟税务计算
          result = { taxDue: rawData.amount * 0.13, region: rawData.region };
          break;
        default:
          result = { status: 'processed' };
      }

      // 3. 重新加密输出
      const outIv = crypto.randomBytes(12);
      const cipher = crypto.createCipheriv('aes-256-gcm', this.TEE_KEY, outIv);
      let encryptedOut = cipher.update(JSON.stringify(result), 'utf8', 'hex');
      encryptedOut += cipher.final('hex');
      const outTag = cipher.getAuthTag();

      logger.info(`[TEE] Secure compute completed for: ${computeLogic}`);
      
      return JSON.stringify({
        data: encryptedOut,
        iv: outIv.toString('base64'),
        tag: outTag.toString('base64')
      });
    } catch (err) {
      logger.error(`[TEE] Computation failed: ${err}`);
      throw new Error('TEE Security Violation');
    }
  }

  /**
   * 数据入仓加密 (由外部调用准备数据)
   */
  static prepareInput(data: any) {
    const iv = crypto.randomBytes(12);
    const cipher = crypto.createCipheriv('aes-256-gcm', this.TEE_KEY, iv);
    let encrypted = cipher.update(JSON.stringify(data), 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return {
      encrypted,
      iv: iv.toString('base64'),
      tag: cipher.getAuthTag().toString('base64')
    };
  }
}
