import type { MikrotikClient } from "./mikrotik.js"

/** Общие PUT iface / peer / address для `/wireguard` и traffic-flow overlay. */
export function toRosBody(obj: Record<string, string | undefined>): Record<string, string> {
  const out: Record<string, string> = {}
  for (const [k, v] of Object.entries(obj)) {
    if (v !== undefined && v !== "") out[k] = v
  }
  return out
}

export function asRosArray<T>(raw: unknown): T[] {
  if (Array.isArray(raw)) return raw as T[]
  if (raw && typeof raw === "object") return [raw as T]
  return []
}

export function rosRowId(row: Record<string, unknown>): string {
  return String(row[".id"] ?? row.id ?? "")
}

export async function putWireguardInterface(
  client: MikrotikClient,
  fields: Record<string, string | undefined>,
): Promise<void> {
  await client.put("/interface/wireguard", toRosBody(fields))
}

export async function putIpAddress(
  client: MikrotikClient,
  address: string,
  iface: string,
): Promise<void> {
  await client.put("/ip/address", { address, interface: iface })
}

export async function putWireguardPeer(
  client: MikrotikClient,
  fields: Record<string, string | undefined>,
): Promise<void> {
  await client.put("/interface/wireguard/peers", toRosBody(fields))
}

export async function patchRosPath(
  client: MikrotikClient,
  path: string,
  fields: Record<string, string | undefined>,
): Promise<void> {
  await client.patch(path, toRosBody(fields))
}
