import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Reflector } from '@nestjs/core';
import { IS_PUBLIC_KEY } from './public.decorator';

@Injectable()
export class SessionGuard implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
    private readonly configService: ConfigService,
  ) {}

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

    const request = context.switchToHttp().getRequest<{
      headers: Record<string, string | undefined>;
    }>();
    const header = request.headers.authorization?.trim() ?? '';
    if (!header.startsWith('Bearer ')) {
      throw new UnauthorizedException('缺少登录令牌');
    }

    const token = header.slice('Bearer '.length).trim();
    const expectedToken =
      this.configService.get<string>('APP_SESSION_TOKEN') ?? 'phase1-demo-token';
    if (!token || token !== expectedToken) {
      throw new UnauthorizedException('登录令牌无效');
    }

    return true;
  }
}

