import type { Client } from 'discord.js';
import { redis } from './redis.js';
import { logger } from './logger.js';

/**
 * Returns true when this process owns shard 0 (or has no shard manager = single process).
 */
export function isPrimaryShard(client: Client): boolean {
  const ids = client.shard?.ids;
  if (!ids || ids.length === 0) {
    return true;
  }
  return ids.includes(0);
}

/**
 * Acquires a short-lived Redis lock. Returns true if this caller owns the lock.
 */
export async function acquireOnceLock(lockKey: string, ttlSeconds: number): Promise<boolean> {
  const result = await redis.set(lockKey, String(Date.now()), 'EX', ttlSeconds, 'NX');
  return result === 'OK';
}

export async function runOncePerCluster(
  lockKey: string,
  ttlSeconds: number,
  fn: () => Promise<void>,
  label: string
): Promise<boolean> {
  const acquired = await acquireOnceLock(lockKey, ttlSeconds);
  if (!acquired) {
    logger.info({ lockKey }, `${label} skipped (another process holds the lock)`);
    return false;
  }
  await fn();
  return true;
}
