import { eq } from "drizzle-orm"
import { db } from "../db/index.js"
import { servers } from "../db/schema.js"
import type { BgpSessionRead } from "../types/server.js"
import { parseBgpSessions } from "./bgp-parse-sessions.js"
import { MikrotikClient } from "./mikrotik.js"

/** Как в UI `/alerts`: `serverName: peerName`. */
export function bgpPeerAlertKey(s: BgpSessionRead): string {
  const sn = String(s.serverName ?? "").trim()
  const nm = String(s.name ?? "").trim()
  return `${sn}: ${nm}`.trim()
}

/** Агрегат BGP-сессий с включённых серверов — как `/api/bgp/sessions`. */
export async function fetchBgpSessionsForAlerts(): Promise<BgpSessionRead[]> {
  const allServers = db.select().from(servers).where(eq(servers.enabled, true)).all()
  const results = await Promise.all(
    allServers.map(async (server) => {
      try {
        const client = MikrotikClient.fromServer(server)
        const raw = await client.getBgpSessions()
        return parseBgpSessions(server, raw)
      } catch {
        return [] as BgpSessionRead[]
      }
    }),
  )
  return results.flat()
}
