<?php

namespace kernel\modules\secure\middlewares;

use JetBrains\PhpStorm\NoReturn;
use kernel\App;
use kernel\helpers\Debug;
use kernel\Middleware;
use kernel\modules\user\service\UserService;
use kernel\Request;

class BearerAuthMiddleware extends Middleware
{
    protected UserService $userService;

    public function __construct()
    {
        $this->userService = new UserService();
    }

    function handler(): void
    {
        $request = new Request();
        $authorization = $request->getHeader("Authorization");
        if ($authorization){
            $authorization = explode(" ", $authorization);
            $type = $authorization[0];
            $token = $authorization[1];
            if ($type === "Bearer"){
                $user = $this->userService->getByAccessToken($token);
                if ($user){
                    if ($user->access_token_expires_at > date("Y-m-d")){
                        App::$user = $user;
                        return;
                    }
                }
            }
        }

        $this->returnError(403);
    }

    #[NoReturn] public function returnError(int $code): void
    {
        http_response_code($code);
        die('Forbidden');
    }
}