import { Injectable, ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(private reflector: Reflector) {
    super();
  }

  canActivate(context: ExecutionContext) {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (isPublic) {
      // 公开接口：尝试解析 JWT（有 token 就解析，没有就跳过）
      // 这样公众端活动列表等接口可以根据用户身份做个性化过滤
      const request = context.switchToHttp().getRequest();
      const authHeader = request.headers?.authorization;
      if (authHeader && authHeader.startsWith('Bearer ')) {
        // 有 token，尝试验证（但失败不阻塞）
        return super.canActivate(context);
      }
      return true;
    }

    return super.canActivate(context);
  }

  // 公开接口 JWT 验证失败时不抛异常，只是 user 为空
  handleRequest(err: any, user: any, info: any, context: ExecutionContext) {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (isPublic && !user) {
      return null; // 公开接口，无用户也放行
    }

    if (err || !user) {
      throw err || new (require('@nestjs/common').UnauthorizedException)();
    }

    return user;
  }
}
