<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureCorrectGuard
{
    /**
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, string $expectedGuard): Response
    {
        $expectedGuard = trim($expectedGuard);

        if ($expectedGuard === '') {
            return $next($request);
        }

        $knownGuards = [
            'web',
            'platform',
        ];

        foreach ($knownGuards as $guard) {
            if ($guard === $expectedGuard) {
                continue;
            }

            if (auth($guard)->check()) {
                abort(404);
            }
        }

        return $next($request);
    }
}
