<?php

namespace Modules\VetClinic\Http\Middleware;

use Closure;
use Modules\VetClinic\Entities\VcRoleLandingPage;

/**
 * On the FIRST GET /home of a session, redirect the user to the landing URL
 * configured for the first matching role they hold (set in VetClinic
 * settings → Role Landing Pages). Subsequent visits to /home in the same
 * session pass through normally so the Home menu link still works.
 */
class ApplyRoleLandingRedirect
{
    public function handle($request, Closure $next)
    {
        if (!$request->isMethod('GET') || !auth()->check()) {
            return $next($request);
        }
        if (!$request->is('home')) {
            return $next($request);
        }
        if ($request->session()->get('vc_landing_consumed')) {
            return $next($request);
        }

        try {
            $user = auth()->user();
            $businessId = $user->business_id ?? $request->session()->get('user.business_id');
            if (!$businessId) {
                return $next($request);
            }
            $roleIds = $user->roles->pluck('id')->all();
            if (empty($roleIds)) {
                return $next($request);
            }
            // FIELD() preserves role-ordering so the user's first role wins.
            $orderedIds = implode(',', array_map('intval', $roleIds));
            $landing = VcRoleLandingPage::where('business_id', $businessId)
                ->whereIn('role_id', $roleIds)
                ->orderByRaw("FIELD(role_id, {$orderedIds})")
                ->value('landing_url');

            $request->session()->put('vc_landing_consumed', true);

            if ($landing && trim($landing) !== '' && ltrim($landing, '/') !== 'home') {
                return redirect($landing);
            }
        } catch (\Throwable $e) {
            // A landing-redirect failure must never block /home from rendering.
        }

        return $next($request);
    }
}
