import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import type { FastifyRequest } from 'fastify';

const EDGE_KEY_HEADER = 'x-hexahost-edge-key';

function getEdgeInternalApiKey(): string {
  return (
    process.env['EDGE_INTERNAL_API_KEY'] ??
    'local-dev-edge-key-change-me-32chars'
  );
}

@Injectable()
export class EdgeInternalGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest<FastifyRequest>();
    const provided = request.headers[EDGE_KEY_HEADER];

    if (typeof provided !== 'string' || provided !== getEdgeInternalApiKey()) {
      throw new UnauthorizedException('Invalid edge internal API key');
    }

    return true;
  }
}
