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

/**
 * MigrationGuard - Guard for protecting database migration endpoints
 *
 * This guard secures migration endpoints by requiring a valid migration token
 * in the request headers. It prevents unauthorized access to database migration
 * operations which could cause data loss or service disruption.
 *
 * Security features:
 * - Token-based authentication via custom header
 * - Environment variable configuration for tokens
 * - Simple but effective protection for administrative operations
 *
 * @example
 * // Apply to migration controller
 * @UseGuards(MigrationGuard)
 * @Controller('migration')
 *
 * @example
 * // Request with migration token
 * POST /migration/up
 * Headers: { 'x-migration-token': 'your-secure-migration-token' }
 */
@Injectable()
export class MigrationGuard implements CanActivate {
  constructor(private configService: ConfigService) {}

  /**
   * Determines if the request is authorized to access migration endpoints
   *
   * Validates the presence and correctness of the migration token in the
   * request headers. Compares it against the token stored in environment
   * variables.
   *
   * @param context - Execution context containing request details
   * @returns true if token is valid, throws BadRequestException otherwise
   * @throws BadRequestException when token is missing or invalid
   *
   * @note Uses simple token comparison - consider adding rate limiting
   * @note Tokens should be long, random strings (UUIDs or cryptographically random)
   */
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();

    // Extract migration token from custom header
    const token = request.headers['x-migration-token'];

    // Get migration token from environment configuration
    const tokenenvvar = this.configService.get('MIGRATION_TOKEN') ?? '';

    // Validate token presence and correctness
    if (token !== tokenenvvar) {
      throw new BadRequestException('Invalid migration token');
    }

    // Token is valid - allow request to proceed
    return true;
  }
}
