import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import type { AccessTokenPayload } from '@pac/types';
import type { TenantScopeContext } from '../../common/decorators/tenant-scope.decorator';

export interface McpAuthContext {
  scope: TenantScopeContext;
  permissions: string[];
}

/**
 * McpAuthService — MCP 端点的 Bearer 鉴权。
 *
 * 复用平台 JWT(AuthModule 配置的 jwt.secret)。token payload 带 hostId/tenantId/clinicIds/permissions,
 * → 派生 TenantScopeContext,每个工具调用据此**强制租户隔离**(与 REST 同一套边界)。
 */
@Injectable()
export class McpAuthService {
  constructor(private readonly jwt: JwtService) {}

  async verifyBearer(authHeader: string | undefined): Promise<McpAuthContext> {
    if (!authHeader?.startsWith('Bearer ')) {
      throw new UnauthorizedException('缺 Bearer token');
    }
    const token = authHeader.slice('Bearer '.length).trim();
    let payload: AccessTokenPayload;
    try {
      payload = await this.jwt.verifyAsync<AccessTokenPayload>(token);
    } catch {
      throw new UnauthorizedException('token 无效或已过期');
    }
    if (!payload?.hostId || !payload?.tenantId) {
      throw new UnauthorizedException('token payload 缺 host/tenant');
    }
    return {
      scope: {
        hostId: payload.hostId,
        tenantId: payload.tenantId,
        clinicIds: payload.clinicIds ?? [],
        sourceUnits: payload.sourceUnits ?? [],
        userId: payload.sub,
      },
      permissions: payload.permissions ?? [],
    };
  }
}
