const redis = require('ioredis');

const connectionsToken = "sensors_pending";
const connectedSensorsKey = "sensors";


const client = new redis({
    host: process.env.REDIS_HOST,
    port: parseInt(process.env.REDIS_PORT),
    password: process.env.REDIS_PASSWORD,
    maxRetriesPerRequest: 3,
    lazyConnect: true,
    retryStrategy(times) {
        const delay = Math.min(times * 50, 2000);
        return delay;
    }
});

client.on('error', (error) => {
    console.error('Redis error', error);
});

client.on('connect', () => {
    console.log('Connected to Redis');
});

client.on('reconnecting', () => {
    console.log('Reconnecting to Redis');
});

async function configure() {
    try {
        await client.connect();
        await client.ping();
        console.log('Redis connection established');
    } catch (err) {
        console.error('Failed to connect to Redis', err);
    }
}

function connected() {
    return client.status === 'ready';
}

async function checkRedis() {
    try {
        if (client.status !== 'ready') {
            await client.connect().catch(() => {});
        }
        await client.ping();
        return true;
    } catch (err) {
        return false;
    }
}

/**
 * 
 * @param {*} sensor 
 * @param {*} status 
 * @param {*} timestamp 
 */
async function appendAsConnection(sensor, status, timestamp) {
    try {
        await client.hset(`sensor:${sensor}`, 'status', status, 'timestamp', timestamp);
    } catch (err) {
        console.error('Redis append error', err);
    }
}

/**
 * Recupera i valori di un campo specifico per una chiave data.
 * @param {String} name - la chiave da cui leggere, es. "sensor:123" 
 * @param {String} from - il nome del campo da leggere, es. "status" o "timestamp"
 * @returns {Object} un oggetto contenente i valori del campo richiesto
 */
async function query(name, from) {
    const key = `${from}:${name}`;
    return await client.hgetall(key);
}

/**
 * Crea un token temporaneo per una nuova connessione WebSocket, scade dopo 5 secondi.
 * @returns {string} il token
 */
async function createConnectionToken(sensor) {
    const crypto = require('crypto');
    const token = crypto.randomBytes(32).toString('hex');
    const key = `${connectionsToken}:${token}`;
    await client.set(key, sensor, 'EX', 5);
    return token;
}

/**
 * Verifica e consuma un token di connessione.
 * @returns {string|null} il nome del sensore se valido, null altrimenti
 */
async function consumeConnectionToken(token) {
    const key = `${connectionsToken}:${token}`;
    const sensor = await client.get(key);
    if (sensor) {
        await client.del(key);
    }
    return sensor;
}

/**
 * Restituisce tutte le chiavi che corrispondono a un prefisso.
 * @param {String} from - il prefisso da cercare, es. "sensor", "ws_token"
 * @returns {string[]} lista di chiavi trovate
 */
async function queryAll(from) {
    const keys = [];
    let cursor = '0';
    do {
        const [next, found] = await client.scan(cursor, 'MATCH', `${from}:*`, 'COUNT', 100);
        cursor = next;
        keys.push(...found);
    } while (cursor !== '0');
    return keys;
}

configure();

async function hset(key, ...args) {
    return client.hset(key, ...args);
}

async function del(key) {
    return client.del(key);
}

module.exports = { checkRedis, appendAsConnection, createConnectionToken, consumeConnectionToken, query, queryAll, hset, del };