import { getAlertState, upsertAlertState, type AlertState } from "../db.js";

export type TransitionAction = "fire" | "resolve" | null;

export function evaluateTransition(
  ruleId: string,
  targetKey: string,
  isBreaching: boolean,
  cooldownSeconds: number,
): TransitionAction {
  const now = new Date().toISOString();
  const existing: AlertState = getAlertState(ruleId, targetKey) ?? {
    rule_id: ruleId,
    target_key: targetKey,
    state: "ok",
    fired_at: null,
    last_notified_at: null,
  };

  if (existing.state === "ok") {
    if (!isBreaching) return null;

    upsertAlertState({
      rule_id: ruleId,
      target_key: targetKey,
      state: "firing",
      fired_at: now,
      last_notified_at: now,
    });
    return "fire";
  }

  // state === 'firing'
  if (!isBreaching) {
    upsertAlertState({
      rule_id: ruleId,
      target_key: targetKey,
      state: "ok",
      fired_at: null,
      last_notified_at: now,
    });
    return "resolve";
  }

  const lastNotified = existing.last_notified_at ? new Date(existing.last_notified_at).getTime() : 0;
  const elapsed = (Date.now() - lastNotified) / 1000;
  if (elapsed >= cooldownSeconds) {
    upsertAlertState({
      ...existing,
      last_notified_at: now,
    });
    return "fire";
  }

  return null;
}
