<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class BlockSeoSpamRequests
{
    /**
     * Block injected SEO-spam query strings (?sitemap123.xml, ?products/123…).
     */
    public function handle(Request $request, Closure $next)
    {
        $query = $request->getQueryString() ?? '';

        if ($query !== '' && (
            preg_match('/(^|&)sitemap\d+\.xml/i', $query)
            || preg_match('/(^|&)products\/\d+/i', $query)
            || preg_match('/(^|&)course\/\d+/i', $query)
        )) {
            Log::channel('seo')->warning('Blocked SEO spam query string', [
                'uri' => $request->getRequestUri(),
                'query' => $query,
                'ip' => $request->ip(),
            ]);

            return response('Gone', 410, [
                'X-Robots-Tag' => 'noindex, nofollow',
                'X-Sitemap-Source' => 'blocked-seo-spam',
            ]);
        }

        return $next($request);
    }
}
