import { getRedis } from "@/lib/redis";
import { WORKER_HEARTBEAT_TTL_SECONDS } from "@/lib/constants/rpa";

const pauseKey = (workerId: string) => `worker:pause:${workerId}`;
const heartbeatKey = (workerId: string) => `worker:heartbeat:${workerId}`;

export async function heartbeat(workerId: string): Promise<void> {
  await getRedis().set(
    heartbeatKey(workerId),
    Date.now().toString(),
    "EX",
    WORKER_HEARTBEAT_TTL_SECONDS,
  );
}

export async function isWorkerPaused(workerId: string): Promise<boolean> {
  const exists = await getRedis().exists(pauseKey(workerId));
  return exists === 1;
}

export async function pauseWorker(
  workerId: string,
  durationMinutes: number,
): Promise<void> {
  const ttlSeconds = Math.max(60, durationMinutes * 60);
  await getRedis().set(pauseKey(workerId), "1", "EX", ttlSeconds);
}

export async function listWorkerHeartbeats(): Promise<
  Array<{ workerId: string; lastSeenMs: number | null }>
> {
  const redis = getRedis();
  const keys = await redis.keys("worker:heartbeat:*");
  const workers: Array<{ workerId: string; lastSeenMs: number | null }> = [];

  for (const key of keys) {
    const workerId = key.replace("worker:heartbeat:", "");
    const raw = await redis.get(key);
    workers.push({
      workerId,
      lastSeenMs: raw ? Number(raw) : null,
    });
  }

  return workers;
}

export async function getWorkerPauseRemaining(
  workerId: string,
): Promise<number> {
  const ttl = await getRedis().ttl(pauseKey(workerId));
  return ttl > 0 ? ttl : 0;
}
