<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

class EnsureTokenIsValid
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if ($this->checkForCodeSession($request->query("codeSession"))) {
            return $next($request);

        } else {
            return  response()->json([], 401);
        }

    }

    public function checkForCodeSession($codeSession): bool
    {
        $check = DB::table("users")->where("code_session", "$codeSession")->first();
        if ($check) {
            return true;
        } else {
            return  false;
        }
    }
}
