<?php

namespace App\Http\Middleware;

use App\Tenancy\TenantManager;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * Defense in depth: even though Sanctum auth + TenantScope should isolate
 * tenants, this middleware EXPLICITLY rejects any request where the
 * authenticated user's company_id does not match the resolved tenant.
 *
 * Stops the entire class of "stolen token used on wrong subdomain" attacks.
 */
class EnsureTokenMatchesTenant
{
    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();
        $tenant = app(TenantManager::class)->current();

        if (! $user || ! $tenant) {
            throw new AccessDeniedHttpException('Tenant context required.');
        }

        if ($user->company_id !== $tenant->id) {
            throw new AccessDeniedHttpException('Token does not belong to this tenant.');
        }

        return $next($request);
    }
}
