<?php

namespace App\Http\Middleware;

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

/**
 * Shares the signed-in account with views. CRM data is scoped per account by
 * the user's public_id (owner_ref); today every user acts as their own
 * account (team support graduates here later, like the platform pattern).
 */
class SetActingAccount
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($user = $request->user()) {
            $request->attributes->set('actingAccount', $user);

            if (! $request->is('api/*')) {
                View::share('actingAccount', $user);
            }
        }

        return $next($request);
    }
}
