<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Symfony\Component\HttpFoundation\Response;

class ThrottleSocialPublishing
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Check if this is a request to schedule a post
        if ($request->isMethod('post') && $request->routeIs('brand.scheduled-posts.store')) {
            $user = auth()->user();
            $key = 'social_publish_' . $user->id;
            
            // Allow 10 posts per minute per user
            if (RateLimiter::tooManyAttempts($key, 10)) {
                return back()->with('error', 'Too many posts scheduled. Please wait before scheduling more.');
            }
            
            RateLimiter::hit($key);
        }
        
        return $next($request);
    }
}
