<?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'),
                'ha'      => redirect()->route('ha-claims.index'),
                default   => redirect()->route('clients.index'),
            };
        }

        // Enforce workspace whitelist
        /** @var \App\Models\User\User $user */
        $user = $request->user();
        if ($user && ! $user->canAccessWorkspace($required)) {
            abort(403, 'You do not have access to this workspace.');
        }

        return $next($request);
    }
}
