<?php

namespace Modules\VetPortal\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

/**
 * Guards the public pet-owner portal. Unauthenticated visitors are sent to the
 * portal login (NOT the ERP admin login). Also makes `pet_owner` the active
 * guard so auth()->user() resolves the portal account inside portal controllers.
 */
class PortalAuthenticate
{
    public function handle($request, Closure $next)
    {
        if (!Auth::guard('pet_owner')->check()) {
            return redirect()->route('vp.portal.login');
        }

        $account = Auth::guard('pet_owner')->user();
        if (!$account->enabled) {
            Auth::guard('pet_owner')->logout();
            return redirect()->route('vp.portal.login')
                ->withErrors(['email' => 'This portal account has been disabled.']);
        }

        $settings = \Modules\VetPortal\Entities\VpPortalSetting::forBusiness($account->business_id);
        if (!$settings->enabled) {
            Auth::guard('pet_owner')->logout();
            return redirect()->route('vp.portal.login')
                ->withErrors(['email' => 'The portal is currently unavailable.']);
        }

        // Make the portal guard the default so auth() works in controllers/views.
        Auth::shouldUse('pet_owner');

        return $next($request);
    }
}
