<?php

namespace App\Http\Middleware;

use App\Services\UserLanding;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Send users who cannot reach the dashboard straight to the first module they
 * *can* access (e.g. a sales rep lands on Sales Orders). Purely permission-driven —
 * the next accessible seeded menu item wins, with no role-name hardcoding.
 *
 * Adapted for the `app` Filament panel (docs/migration-plan.md): the source
 * app checked Inertia's literal `/dashboard` and `/` paths; here the
 * equivalent "home" is the tenant panel's own root path.
 */
class RedirectToAccessibleHome
{
    /**
     * Path of the tenant Filament panel (App\Providers\Filament\TenantPanelProvider::path()).
     */
    private const PANEL_PATH = 'app';

    /**
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        $path = trim($request->path(), '/');

        // Path tenancy: the panel path is "{workspace}/app" — "{workspace}/app" is
        // the dashboard landing, so match the suffix rather than the bare
        // panel path.
        $landingOnDashboard = $path === self::PANEL_PATH
            || $path === ''
            || str_ends_with($path, '/'.self::PANEL_PATH);

        if ($user
            && $landingOnDashboard
            && ! $user->isFullAdmin()
            && ! $user->hasPermissionTo('dashboard.access')) {
            $home = UserLanding::urlFor($user);

            if ($home !== url($path)) {
                return redirect($home);
            }
        }

        return $next($request);
    }
}
