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

@Injectable()
export class InternalCryptoKeyGuard implements CanActivate {
  constructor(private readonly config: ConfigService) {}

  canActivate(context: ExecutionContext): boolean {
    const allowedKeys = [
      this.config.get<string>('INTERNAL_CRYPTO_API_KEY'),
      this.config.get<string>('PUBLIC_API_KEY'),
    ].filter((key): key is string => Boolean(key?.trim()));
    if (!allowedKeys.length) throw new UnauthorizedException('Internal crypto API key is not configured');

    const request = context.switchToHttp().getRequest<Request>();
    const headerKey = request.header('x-api-key');
    const authHeader = request.header('authorization');
    const bearerKey = authHeader?.startsWith('ApiKey ') ? authHeader.slice('ApiKey '.length) : undefined;

    if ((headerKey && allowedKeys.includes(headerKey)) || (bearerKey && allowedKeys.includes(bearerKey))) return true;
    throw new UnauthorizedException('Invalid API key');
  }
}
