import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { createHash, timingSafeEqual } from 'node:crypto';

@Injectable()
export class InternalAccessGuard implements CanActivate {
  canActivate(context: ExecutionContext) {
    const request = context.switchToHttp().getRequest<{ headers: Record<string, string | string[] | undefined> }>();
    const expected = process.env.INTERNAL_API_SECRET;
    const receivedRaw = request.headers['x-internal-api-secret'];
    const received = Array.isArray(receivedRaw) ? receivedRaw[0] : receivedRaw;
    if (!expected || !received) throw new UnauthorizedException('INTERNAL_AUTH_REQUIRED');
    const a = createHash('sha256').update(received).digest();
    const b = createHash('sha256').update(expected).digest();
    if (a.length !== b.length || !timingSafeEqual(a, b)) throw new UnauthorizedException('INTERNAL_AUTH_INVALID');
    return true;
  }
}
