import { promisify } from 'node:util';
import redisLock, { unlockFunction } from 'redis-lock';
import { redisClient } from '@/db/redis.js';

/**
 * Retry delay (ms) for lock acquisition
 */
const retryDelay = 100;

const lock: (key: string, timeout?: number) => Promise<() => void>
	= redisClient
		? promisify(redisLock(redisClient, retryDelay))
		: async () => () => { };

/**
 * Get AP Object lock
 * @param uri AP object ID
 * @param timeout Lock timeout (ms), The timeout releases previous lock.
 * @returns Unlock function
 */
export async function getApLock(uri: string, timeout: number = 30 * 1000): Promise<unlockFunction> {
	return await lock(`ap-object:${uri}`, timeout);
}

export async function getFetchInstanceMetadataLock(host: string, timeout: number = 30 * 1000): Promise<unlockFunction> {
	return await lock(`instance:${host}`, timeout);
}

export async function getChartInsertLock(lockKey: string, timeout: number = 30 * 1000): Promise<unlockFunction> {
	return await lock(`chart-insert:${lockKey}`, timeout);
}
