<?php

namespace App\Http\Middleware;

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

class EnsureUserHasWorkspace
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $workspaceId = $request->session()->get('current_workspace_id');

        if (! $workspaceId) {
            return redirect()->route('dashboard')
                ->with('error', __('Please select a workspace first.'));
        }

        $user = $request->user();
        $hasAccess = $user->workspaces()->where('workspaces.id', $workspaceId)->exists();

        if (! $hasAccess) {
            $request->session()->forget('current_workspace_id');

            return redirect()->route('dashboard')
                ->with('error', __('You do not have access to this workspace.'));
        }

        return $next($request);
    }
}
