<?php

namespace App\Http\Middleware;

use App\Models\FolderInvitation;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ValidateFolderInvitation
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $token = $request->route('token');

        $invitation = FolderInvitation::query()
            ->where('token', $token)
            ->with(['folder.client', 'folder.assignee', 'folder.creator'])
            ->first();

        if (! $invitation || ! $invitation->isValid()) {
            abort(404, 'Lien invalide ou expiré.');
        }

        $request->attributes->set('folder_invitation', $invitation);

        return $next($request);
    }
}
