import { Controller, Post, Req, Res } from '@nestjs/common';
import type { Request, Response } from 'express';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { Public } from '../../common/decorators/public.decorator';
import { McpAuthService } from './mcp-auth.service';
import { McpServerFactory } from './mcp-server.factory';

/**
 * McpController — PAC MCP Server 入口(Streamable HTTP,无状态)。
 *
 * 端点:POST /pac/v1/mcp
 * 鉴权:`Authorization: Bearer <平台 JWT>`(@Public 跳过全局 JWT guard,本控制器自验并派生 scope)。
 *
 * 每个请求:验签 → 构建 scoped McpServer(工具继承租户隔离)→ 无状态 transport.handleRequest。
 * 无状态(sessionIdGenerator:undefined + enableJsonResponse:true):可过普通 LB,无 session store。
 */
@ApiTags('mcp')
@Controller('mcp')
export class McpController {
  constructor(
    private readonly auth: McpAuthService,
    private readonly factory: McpServerFactory,
  ) {}

  @Post()
  @Public()
  @ApiOperation({
    summary: 'PAC MCP server(Streamable HTTP)— 暴露患者只读工具给 agent;Bearer JWT 鉴权',
  })
  async handle(@Req() req: Request, @Res() res: Response): Promise<void> {
    let ctx;
    try {
      ctx = await this.auth.verifyBearer(req.headers['authorization']);
    } catch {
      res
        .status(401)
        .json({ jsonrpc: '2.0', error: { code: -32001, message: 'Unauthorized' }, id: null });
      return;
    }

    const server = this.factory.build(ctx);
    const transport = new StreamableHTTPServerTransport({
      sessionIdGenerator: undefined,
      enableJsonResponse: true,
    });
    res.on('close', () => {
      void transport.close();
      void server.close();
    });
    await server.connect(transport);
    await transport.handleRequest(req, res, req.body);
  }
}
