<?php

namespace App\Http\Middleware;

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

class ValidateClientPortalToken
{
    /**
     * 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 = DeclarationInvitation::query()
            ->where('token', $token)
            ->with(['declaration.client', 'declaration.assignee', 'declaration.creator'])
            ->first();

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

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

        return $next($request);
    }
}
