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

@Injectable()
export class InternalAuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest<Request>();
    const key =
      request.headers['x-internal-api-key'] as string | undefined;

    const expected =
      process.env.INTERNAL_API_KEY ||
      process.env.RAG_WORKER_SECRET;

    if (!expected) {
      throw new UnauthorizedException('内部服务未配置 API Key');
    }

    if (!key || key !== expected) {
      throw new UnauthorizedException('内部服务认证失败');
    }

    return true;
  }
}
