<?php

namespace App\Http\Middleware;

use App\Models\UploadSession;
use App\Services\Files\StorageUsageService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\RateLimiter;

class UploadRateLimitMiddleware
{
    public function __construct(
        protected StorageUsageService $usageService
    ) {}

    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();

        if (! $user) {
            return $next($request);
        }

        $quotas = config('file_upload.quotas', []);
        $roleQuotas = $quotas[$user->role] ?? $quotas['user'] ?? [];

        // Check concurrent uploads
        $maxConcurrent = $roleQuotas['concurrent_uploads'] ?? 3;
        if ($maxConcurrent > 0) {
            $concurrentCount = $this->usageService->getConcurrentUploadCount($user);

            if ($concurrentCount >= $maxConcurrent) {
                return response()->json([
                    'message' => "Maximum concurrent uploads ({$maxConcurrent}) reached. Please wait for current uploads to complete.",
                ], Response::HTTP_TOO_MANY_REQUESTS);
            }
        }

        // Check daily upload count
        $maxDailyUploads = $roleQuotas['daily_uploads'] ?? -1;
        if ($maxDailyUploads > 0) {
            $dailyCount = $this->usageService->getDailyUploadCount($user);

            if ($dailyCount >= $maxDailyUploads) {
                return response()->json([
                    'message' => "Daily upload limit ({$maxDailyUploads}) reached. Please try again tomorrow.",
                ], Response::HTTP_TOO_MANY_REQUESTS);
            }
        }

        // Apply rate limiting for chunk uploads
        if ($request->is('*/upload/*') && $request->isMethod('POST')) {
            $key = 'upload:'.$user->id;

            if (RateLimiter::tooManyAttempts($key, 60)) { // 60 chunks per minute
                $seconds = RateLimiter::availableIn($key);

                return response()->json([
                    'message' => "Too many upload requests. Please wait {$seconds} seconds.",
                ], Response::HTTP_TOO_MANY_REQUESTS);
            }

            RateLimiter::hit($key, 60); // Decay after 60 seconds
        }

        return $next($request);
    }
}
