<?php

namespace App\Http\Middleware;

use App\Models\AppSession;
use Closure;

class ProAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $sessionKey = $request->cookie('sessionKey');
        $appSession = AppSession::where('session_key', $sessionKey)->where('is_active', true)->first();
        $authenticated = $sessionKey && $appSession;
       
        if (!$authenticated) {
            $authUrl = config('stag.authUrl');
            if(!$authUrl){
                echo('AUTH_URL is not specified.');
                exit;
            }
            return redirect($authUrl);
        }

        return $next($request);
    }
}
