<?php

declare(strict_types=1);

namespace App\Services;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtService
{
    private string $secret;
    private int $ttlMinutes;
    private int $refreshTtlDays;

    public function __construct()
    {
        $this->secret = $_ENV['JWT_SECRET'] ?? '';
        $this->ttlMinutes = (int) ($_ENV['JWT_TTL_MINUTES'] ?? 60);
        $this->refreshTtlDays = (int) ($_ENV['JWT_REFRESH_TTL_DAYS'] ?? 30);
    }

    public function issueAccessToken(int $userId, string $rol): string
    {
        $now = time();
        $payload = [
            'sub' => $userId,
            'rol' => $rol,
            'type' => 'access',
            'iat' => $now,
            'exp' => $now + ($this->ttlMinutes * 60),
        ];

        return JWT::encode($payload, $this->secret, 'HS256');
    }

    public function issueRefreshToken(int $userId): string
    {
        $now = time();
        $payload = [
            'sub' => $userId,
            'type' => 'refresh',
            'iat' => $now,
            'exp' => $now + ($this->refreshTtlDays * 86400),
        ];

        return JWT::encode($payload, $this->secret, 'HS256');
    }

    /**
     * @return array<string, mixed>
     * @throws \Firebase\JWT\ExpiredException|\UnexpectedValueException
     */
    public function decode(string $token): array
    {
        $decoded = JWT::decode($token, new Key($this->secret, 'HS256'));

        return (array) $decoded;
    }
}
