import { eq } from "drizzle-orm"
import { db } from "../../db/index.js"
import { alertEnginePrevLive } from "../../db/schema.js"

export type PrevLiveKind = "gre" | "bgp"

/** Предыдущие строковые состояния (GRE: up|down|degraded; BGP: state как с роутера). */
export type PrevLiveStringMap = Record<string, string>

function safeParseMap(json: string | null | undefined): PrevLiveStringMap {
  if (!json || json.trim() === "") return {}
  try {
    const v = JSON.parse(json) as unknown
    if (v == null || typeof v !== "object" || Array.isArray(v)) return {}
    return v as PrevLiveStringMap
  } catch {
    return {}
  }
}

export function loadPrevLiveMap(kind: PrevLiveKind): PrevLiveStringMap {
  const row = db
    .select()
    .from(alertEnginePrevLive)
    .where(eq(alertEnginePrevLive.kind, kind))
    .limit(1)
    .all()[0]
  return safeParseMap(row?.payloadJson)
}

export function savePrevLiveMap(kind: PrevLiveKind, map: PrevLiveStringMap) {
  const payloadJson = JSON.stringify(map)
  const existing = db
    .select()
    .from(alertEnginePrevLive)
    .where(eq(alertEnginePrevLive.kind, kind))
    .limit(1)
    .all()[0]
  if (existing) {
    db.update(alertEnginePrevLive)
      .set({ payloadJson, updatedAt: new Date().toISOString() })
      .where(eq(alertEnginePrevLive.kind, kind))
      .run()
  } else {
    db.insert(alertEnginePrevLive).values({ kind, payloadJson, updatedAt: new Date().toISOString() }).run()
  }
}
