import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

/**
 * 管理员 JWT Guard
 *
 * 验证 identity-service 管理员登录颁发的 JWT（type: 'admin'）。
 * 用于保护 online-count、online-history、dau 等聚合查询接口。
 */
@Injectable()
export class AdminGuard implements CanActivate {
  constructor(private readonly jwtService: JwtService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const token = this.extractTokenFromHeader(request);
    if (!token) throw new UnauthorizedException('缺少认证令牌');

    try {
      const payload = await this.jwtService.verifyAsync(token);
      if (payload.type !== 'admin') throw new UnauthorizedException('需要管理员权限');
      request.user = {
        adminId: payload.sub,
        email: payload.email,
        role: payload.role,
        type: 'admin',
      };
    } catch {
      throw new UnauthorizedException('令牌无效或已过期');
    }

    return true;
  }

  private extractTokenFromHeader(request: any): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
}
