<?php

namespace App\Http\Middleware;

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

class RequireWorkspace {
    /**
     * Redirect to the home of the user's current workspace if they try to
     * access a route that belongs to a different workspace.
     *
     * Usage: ->middleware('workspace:ha')  or  ->middleware('workspace:pension')
     */
    public function handle(Request $request, Closure $next, string $required): Response {
        $current = session('workspace', 'ha');

        if ($current !== $required) {
            return match($current) {
                'pension' => redirect()->route('pension-cases.index'),
                'wills'   => redirect()->route('wills-cases.index'),
                default   => redirect()->route('clients.index'),
            };
        }

        return $next($request);
    }
}
