<?php

namespace App\Models;

use App\Util\Helper;
use App\Util\JWTManager;

class TokenMiddleware
{
    protected array $tokenData;
    private string $tokenBearer;
    public function __invoke()
    {
        $this->getBearer(); // get token from header
        $this->validateToken();
    }

    public function getData(): array
    {
        return $this->tokenData;
    }

    private function validateToken()
    {
        $serverToken = $this->tokenBearer ?? '';
        $jwtManager = new JWTManager;
        if (!$jwtManager->isTokenValid($serverToken)) {
            $this->handleError(401, 'Sorry, you are not logged in.');
        }

        if($jwtManager->isTokenExpired($serverToken)) {
            $this->handleError(401, 'Sorry, your token has expired.');
        }

        $this->tokenData = $jwtManager->getTokenData($serverToken);
    }

    private function getStatusCodeText($statusCode)
    {
        $statusTexts = [
            401 => 'Unauthorized',
            403 => 'Forbidden',
            404 => 'Not Found',
            200 => 'OK',
            400 => 'Bad Request',
            422 => 'Unprocessable Entity',
            204 => 'No Content',
        ];
        return $statusTexts[$statusCode] ?? 'Unknown Status';
    }

    private function getBearer(): void
    {
        $bearerToken = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        if (empty($bearerToken)) {
            $this->handleError(400, 'Unauthorized access.');
        }
        $this->tokenBearer = str_replace('Bearer ', '', $bearerToken);
    }

    private function handleError($statusCode, $message)
    {
        header("HTTP/1.1 $statusCode " . $this->getStatusCodeText($statusCode));
        Helper::jsonResult(['status' => false, 'message' => $message]);
        exit;
    }
}