import type { IntegrationAdapter, Resource } from './types.js'

interface NetbirdPeer {
  name: string
  hostname?: string
  connected: boolean
  ip?: string
  os?: string
}

function baseUrlFor(config: Record<string, string>) {
  return (config.baseUrl?.replace(/\/$/, '')) || 'https://api.netbird.io'
}

export const netbird: IntegrationAdapter = {
  async testConnection(config, secrets) {
    const apiKey = secrets.apiKey
    if (!apiKey) return { ok: false, message: 'Missing API key' }
    try {
      const res = await fetch(`${baseUrlFor(config)}/api/peers`, {
        headers: { Authorization: `Token ${apiKey}` },
      })
      if (!res.ok) return { ok: false, message: `HTTP ${res.status}` }
      return { ok: true, message: 'Connected' }
    } catch (err) {
      return { ok: false, message: err instanceof Error ? err.message : 'Connection failed' }
    }
  },

  async listResources(config, secrets): Promise<Resource[]> {
    const apiKey = secrets.apiKey
    if (!apiKey) return []
    const res = await fetch(`${baseUrlFor(config)}/api/peers`, {
      headers: { Authorization: `Token ${apiKey}` },
    })
    if (!res.ok) return []
    const peers = (await res.json()) as NetbirdPeer[]
    return peers.map((p) => ({
      name: p.name || p.hostname || p.ip || 'unknown peer',
      status: p.connected ? 'healthy' : 'critical',
      detail: p.connected ? `Online — ${p.ip ?? ''}`.trim() : 'Offline',
    }))
  },
}
