<?php

namespace App\Http\Middleware;

use App\Domain\Shared\Context\BranchContext;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Make sure every authenticated request knows which branch it is in.
 *
 * Seeding used to happen inside BranchSwitcher::mount(), which meant a getter
 * with a write side effect that ran only on pages rendering the topbar — and
 * which re-pinned a concrete branch over the "all branches" null on every
 * render. Doing it here instead makes the switcher a pure reader.
 *
 * Runs after SetCurrentAcademy, which binds `current_academy`; BranchContext
 * needs that to know which branches exist.
 */
class ResolveBranchContext
{
    public function __construct(private BranchContext $branch)
    {
    }

    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if ($user && ! $this->branch->isResolved()) {
            $this->branch->resolveForUser($user);
        }

        return $next($request);
    }
}
