<?php

class TokenService {

    private static string $secret = 'Temp2025_CRYPT';

    public static function generar(array $payload, int $expiraEnSegundos = 3600): string {
        $payload['exp'] = time() + $expiraEnSegundos;
        $data = json_encode($payload);
        $firma = hash_hmac('sha256', $data, self::$secret);
        return base64_encode($data . '::' . $firma);
    }

    public static function validar(string $token): array {
        $decoded = base64_decode($token);
        if (!$decoded || !str_contains($decoded, '::')) {
            throw new Exception('Token inválido');
        }

        [$data, $firma] = explode('::', $decoded);
        $firmaValida = hash_hmac('sha256', $data, self::$secret);

        if (!hash_equals($firmaValida, $firma)) {
            throw new Exception('Firma inválida');
        }

        $payload = json_decode($data, true);

        if ($payload['exp'] < time()) {
            throw new Exception('Token expirado');
        }

        return $payload;
    }
}
