import {
  CIRCUIT_FAILURE_THRESHOLD,
  CIRCUIT_TTL_SECONDS,
} from "@/lib/constants/cache";
import { getRedis } from "@/lib/redis";

const CIRCUIT_KEY = "circuit:rpa";
const FAILURE_KEY = "circuit:rpa:failures";

export async function isCircuitOpen(): Promise<boolean> {
  const state = await getRedis().get(CIRCUIT_KEY);
  return state === "open";
}

export async function openCircuit(): Promise<void> {
  await getRedis().set(CIRCUIT_KEY, "open", "EX", CIRCUIT_TTL_SECONDS);
}

export async function closeCircuit(): Promise<void> {
  const redis = getRedis();
  await redis.del(CIRCUIT_KEY);
  await redis.del(FAILURE_KEY);
}

/** 记录 RPA 失败；连续 ≥3 次自动熔断 */
export async function recordRpaFailure(): Promise<void> {
  const redis = getRedis();
  const count = await redis.incr(FAILURE_KEY);

  if (count === 1) {
    await redis.expire(FAILURE_KEY, CIRCUIT_TTL_SECONDS);
  }

  if (count >= CIRCUIT_FAILURE_THRESHOLD) {
    await openCircuit();
  }
}

/** RPA 成功时重置失败计数 */
export async function recordRpaSuccess(): Promise<void> {
  await getRedis().del(FAILURE_KEY);
}
