import { createHash } from "node:crypto";
import { decode } from "hono/jwt";

/**
 * Hashes a token using SHA256 to avoid storing sensitive data in Redis.
 */
export function hashToken(token: string): string {
    return createHash("sha256").update(token).digest("hex");
}

/**
 * Extracts the expiration time (Unix timestamp) from a JWT token.
 * Returns 0 if the token is invalid or has no exp claim.
 */
export function getTokenExpiry(token: string): number {
    try {
        const { payload } = decode(token);
        return (payload.exp as number) || 0;
    } catch (err) {
        return 0;
    }
}

export const REDIS_KEYS = {
    blacklistAdmin: (hash: string) => `blacklist:admin:${hash}`,
    cache: (key: string) => `cache:${key}`,
};

/**
 * Invalidates Redis cache keys starting with a specific prefix.
 * Warning: Uses KEYS command which can be expensive on very large datasets.
 */
export async function invalidateCacheByPrefix(redis: any, prefix: string) {
    const pattern = `${REDIS_KEYS.cache(prefix)}*`;
    const keys = await redis.keys(pattern);
    if (keys && keys.length > 0) {
        await redis.del(...keys);
    }
}
