/**
 * PR14 Teams webhook controller —— Bot Framework 入站 POST /api/agent/teams/webhook。
 *
 * **本文件是 skeleton**：路由 + JWT 验证占位 + activity 解析骨架。
 * 真实启用前需到位：
 * - Azure Bot Framework 注册（App ID + secret 进 .env：FFAI_TEAMS_APP_ID / FFAI_TEAMS_APP_PASSWORD）
 * - Microsoft 公钥端点（https://login.botframework.com/v1/.well-known/openidconfiguration）拉签名公钥验 JWT
 * - AAD 跨组织假冒测试（红队 fixture）通过
 *
 * 详见 docs/modules/agent/02-architecture.md PR14 段。
 */

import { Controller, Post, Body, Headers, HttpException, HttpStatus } from '@nestjs/common';
import { createLogger } from '@core/observability/logging/config/winston.config';
import type { BotActivity } from './teams.types';

const logger = createLogger('TeamsWebhook');

@Controller('agent/teams')
export class TeamsWebhookController {
  @Post('webhook')
  async handle(
    @Headers('authorization') auth: string | undefined,
    @Body() activity: BotActivity,
  ): Promise<{ ok: boolean; pending?: string }> {
    // ── Step 1：JWT 签名验证（占位）
    // 真实实现：拉 https://login.botframework.com/v1/.well-known/openidconfiguration 公钥
    //           verify `iss=https://api.botframework.com` + `aud=${FFAI_TEAMS_APP_ID}`
    //           expired / wrong issuer → 401
    if (!auth || !auth.startsWith('Bearer ')) {
      throw new HttpException('missing_jwt', HttpStatus.UNAUTHORIZED);
    }
    // TODO PR14 真实化：verifyBotFrameworkJwt(auth.slice(7))

    // ── Step 2：解析 activity 类型
    switch (activity.type) {
      case 'conversationUpdate':
        // 新用户加入对话 → 触发 AAD↔FF AI 配对挑战
        logger.log(`conversationUpdate from=${activity.from.aadObjectId}`);
        return { ok: true, pending: 'pairing_challenge_not_implemented' };
      case 'message':
        // 文本消息 → 转 SDKMessage 走 agent 主流程（pair 已建立的前提下）
        logger.log(`message from=${activity.from.aadObjectId} text=${activity.text?.slice(0, 80)}`);
        return { ok: true, pending: 'message_routing_not_implemented' };
      case 'invoke':
        // Adaptive Card 按钮回调
        logger.log(`invoke from=${activity.from.aadObjectId}`);
        return { ok: true, pending: 'adaptive_card_callback_not_implemented' };
      default:
        return { ok: true };
    }
  }
}
