import assert from "node:assert/strict"
import { eq } from "drizzle-orm"
import { db } from "../../db/index.js"
import { alertEngineConfirmPending } from "../../db/schema.js"
import type { ApiAlertRule } from "../alerts-service.js"
import { computeStabilityReadyMap, deleteConfirmPending } from "./confirm-stability.js"

const ruleId = "test-confirm-stability-recovery-bypass"

deleteConfirmPending(ruleId)

const baseRule: ApiAlertRule = {
  id: ruleId,
  name: "Server transition",
  type: "server",
  target: "core-1",
  targets: ["core-1"],
  groupId: null,
  condition: "перешёл в offline · восстановился",
  conditions: ["перешёл в offline", "восстановился"],
  severity: "critical",
  enabled: true,
  cooldown: "5м",
  confirmStabilitySec: 120,
  recoveryMode: "always",
  recoveryStabilitySec: null,
  chatId: "",
  lastFiredAt: null,
}

const problemHit = {
  ruleId,
  ruleName: baseRule.name,
  severity: baseRule.severity,
  message: "Сервер: core-1 — перешёл в offline",
  transition: "problem" as const,
  payloadHash: "problem-1",
}

const recoveryHit = {
  ruleId,
  ruleName: baseRule.name,
  severity: baseRule.severity,
  message: "Сервер: core-1 — восстановился",
  transition: "recovery" as const,
  payloadHash: "recovery-1",
}

{
  const m = computeStabilityReadyMap([baseRule], new Map([[ruleId, problemHit]]))
  assert.equal(m.get(ruleId), false, "проблемный переход должен ждать confirmStabilitySec")
}

{
  const m = computeStabilityReadyMap([baseRule], new Map([[ruleId, recoveryHit]]))
  assert.equal(m.get(ruleId), true, "восстановление должно отправляться без задержки")
}

{
  const m = computeStabilityReadyMap([baseRule], new Map([[ruleId, null]]))
  assert.equal(m.get(ruleId), false, "без hit отправка не готова")
  const left = db
    .select()
    .from(alertEngineConfirmPending)
    .where(eq(alertEngineConfirmPending.ruleId, ruleId))
    .limit(1)
    .all()[0]
  assert.equal(left, undefined, "pending должен очищаться после отсутствия hit")
}

console.log("alert-engine confirm-stability tests ok")
