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

@Injectable()
export class CronAuthGuard implements CanActivate {
  constructor(private readonly configService: ConfigService) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest<{ headers: Record<string, string | undefined> }>();
    const expectedSecret = this.configService.get<string>('CRON_SECRET');
    const receivedSecret = request.headers['x-cron-secret'];

    if (!expectedSecret || receivedSecret !== expectedSecret) {
      throw new ForbiddenException('Invalid cron secret');
    }

    return true;
  }
}
