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

/**
 * Guard for internal service-to-service authentication
 * Requires X-Internal-Service-Token header with valid service secret
 */
@Injectable()
export class InternalServiceGuard implements CanActivate {
  constructor(private configService: ConfigService) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const serviceToken = request.headers['x-internal-service-token'];
    const requestSource = request.headers['x-request-source'];

    if (!serviceToken) {
      throw new UnauthorizedException('Missing internal service token');
    }

    if (!requestSource) {
      throw new UnauthorizedException('Missing request source header');
    }

    // Validate token against configured secret
    const validToken = this.configService.get<string>('INTERNAL_SERVICE_SECRET');
    
    if (!validToken) {
      throw new UnauthorizedException(
        'INTERNAL_SERVICE_SECRET not configured — cannot validate internal requests',
      );
    }

    if (serviceToken !== validToken) {
      throw new UnauthorizedException('Invalid internal service token');
    }

    // Attach service info to request
    request.internalService = {
      source: requestSource,
      authenticated: true,
    };

    return true;
  }
}
