<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\User;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserBelongsToTenant
{
    /**
     * Verify the authenticated user is allowed to operate on the active tenant.
     *
     * The tenant is resolved from the X-Tenant request header by
     * InitializeTenancyByRequestData, which performs no authorisation of its
     * own. Without this check any authenticated user can target any tenant's
     * data simply by changing the header (AUTO-1676). This mirrors the
     * membership check the API-token path already enforces in
     * ApiAuthenticatedRequest.
     *
     * mtc superadmins hold the 'mtc' role under the global (teamless) scope and
     * legitimately manage every tenant, so they are exempt. Every other user
     * must have an explicit tenant_users membership row for the active tenant.
     *
     * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        /** @var User|null $user */
        $user = $request->user();

        if ($user === null || tenant('id') === null) {
            return $next($request);
        }

        if ($this->isSuperAdmin($user) || $this->belongsToTenant($user)) {
            return $next($request);
        }

        return \response('Access Denied', 403);
    }

    private function isSuperAdmin(User $user): bool
    {
        return $user->hasRole('mtc');
    }

    private function belongsToTenant(User $user): bool
    {
        return $user->tenants()->where('tenant_id', tenant('id'))->exists();
    }
}
