<?php

namespace App\Http\Middleware;

use App\Models\AppSession;
use Closure;
use Illuminate\Support\Facades\Http;

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;
       //TODO: confirm app_access
        if (!$authenticated) {
            $authUrl = config('stag.authUrl');
            if(!$authUrl){
                echo('AUTH_URL is not specified.');
                exit;
            }
            return redirect($authUrl . '?from=fe2');
        }

        //log session activity 
        $this->logSessionActivity($sessionKey);

        return $next($request);
    }

    private function logSessionActivity($sessionKey)
    {
        
        $url =  config('stag.backendUrl') . '/session/ping';
        $response = Http::asForm()
            ->withHeaders([
                'sessionKey' => $sessionKey
            ])
            ->post($url,[])
            ->body();
        return $response;
    }
}
