import { redisClient } from './redis.provider';

export async function runWithSimpleLock(
    key: string,
    ttl: number,
    task: () => Promise<void>
): Promise<void> {
    const lockKey = `lock:${key}`;
    console.log(`🚦 Attempting to acquire lock: ${key} with TTL: ${ttl}ms`);

    try {
        const isLocked = await redisClient.set(lockKey, 'locked', 'PX', ttl, 'NX');
        if (!isLocked) {
            console.warn(`⛔ Lock not acquired for ${key}: Already locked`);
            return;
        }

        console.log(`🔒 Lock acquired: ${key}`);
        try {
            await task();
        } finally {
            await redisClient.del(lockKey);
            console.log(`🔓 Lock released: ${key}`);
        }
    } catch (error) {
        console.error(`🔥 Error during lock or task for ${key}:`, error);
    }
}
