<?php

namespace App\Http\Middleware\Solicitor;

use App\Models\Solicitor\Solicitor;
use Closure;
use Illuminate\Http\Request;

class EnsureUserBelongsToSolicitor {
    public function handle(Request $request, Closure $next) {
        if ($request->is('admin*', 'account*', 'workspace', 'workspace/*')) {
            return $next($request);
        }

        $tenant = app(Solicitor::class);
        $user   = auth()->user();

        // Platform user with no workspace selected - send to selector
        if ($user && $user->isPlatformUser() && !$tenant) {
            return redirect()->route('workspace.select');
        }

        if (!$tenant && !$request->is('login', 'logout', '/')) {
            abort(403, 'No solicitor detected.');
        }

        // Regular solicitor user on the wrong portal
        if ($user && $tenant && $user->solicitor_id && $user->solicitor_id != $tenant->id) {
            abort(403, 'You do not have permission to access this solicitor portal.');
        }

        return $next($request);
    }
}
