<?php

namespace App\Http\Middleware\Platform;

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

class EnsurePlatformUser
{
    public function handle(Request $request, Closure $next)
    {
        $user = auth()->user();

        // Prevent impersonated users from reaching admin pages in production
        if ($user->solicitor_id && app()->isProduction() && $request->session()->has('impersonator_id')) {
            abort(403);
        }

        // Platform users must have a workspace selected before accessing any admin page
        if ($user->isPlatformUser() && !app(Solicitor::class)) {
            return redirect()->route('workspace.select');
        }

        return $next($request);
    }
}
