<?php

namespace App\Domain\Token\Repository;

use PDO;
use Illuminate\Database\Connection;
use Psr\Http\Message\ServerRequestInterface as Request;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\SignatureInvalidException;
use Exception;

/**
 * Repository.
 */
class TokenRepository {
    
    /**
     * @var PDO The database connection
     */

    /**
     * Constructor.
     *
     * @param PDO $connection The database connection
     */

    public function __construct() {}

    /**
     * Insert user row.
     *
     * @param array $datos de los usuarios
     *
     * @return int The new ID
     */
    
    public function ValidateToken(Request $request):array{

        $secretKey = 'Blanca@2023.';
        $token = $this->GetTokenFromHeaders($request);

        if(empty($token)) {
            return $this->ErrToken(400, 'Token invalid');
        }

        try {

            $decoded = JWT::decode($token, new Key($secretKey, 'HS256'));
            $exp = date('Y-m-d H:i:s', $decoded->exp);

            $payload = [
                'sub' => $decoded->email,
                'name' => $decoded->name,
                'status' => 'true', 
                'description' => 'Token is valid', 
                'exp' => $exp
            ];

            return $payload;
        } catch (ExpiredException $e) {
            return $this->ErrToken(401, 'El token ha expirado');
        } catch (JsonException $e) {
            return $this->ErrToken(400, 'El token es invalido');
        } catch (SignatureInvalidException $e) {
            return $this->ErrToken(401, 'La firma del token no es valida');
        } catch (Exception $e) {
            return $this->ErrToken(401, 'Acceso denegado');
        }
    }

    public function ErrToken($status, $e): array {

        $payload = [
            'sub' => 'null',
            'name' => 'null',
            'status' => 'false', 
            'description' => $e, 
            'exp' => 'null'
        ];

        return $payload;
    }

    private function GetTokenFromHeaders(Request $request): ?string {

        $header = $request->getHeaderLine('Authorization');

        if(preg_match('/Bearer\s(\S+)/', $header, $matches)) {
            return $matches[1];
        }

        return null;
    }
}