import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Request } from 'express';

@Injectable()
export class ScreenshotTokenGuard implements CanActivate {
  private readonly tokens: Set<string>;

  constructor(private readonly configService: ConfigService) {
    const raw = this.configService.get<string>('SCREENSHOT_API_TOKENS', '');
    this.tokens = new Set(
      raw
        .split(',')
        .map((t) => t.trim())
        .filter(Boolean),
    );
  }

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest<Request>();
    const auth = request.headers.authorization;

    if (!auth?.startsWith('Bearer ')) {
      throw new UnauthorizedException('Missing Bearer token');
    }

    const token = auth.slice(7);
    if (!this.tokens.has(token)) {
      throw new UnauthorizedException('Invalid token');
    }

    return true;
  }
}
