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

export const docker: IntegrationAdapter = {
  async testConnection(config) {
    const baseUrl = config.baseUrl?.replace(/\/$/, '')
    if (!baseUrl) return { ok: false, message: 'Missing baseUrl' }
    try {
      const res = await fetch(`${baseUrl}/version`)
      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): Promise<Resource[]> {
    const baseUrl = config.baseUrl?.replace(/\/$/, '')
    if (!baseUrl) return []
    const res = await fetch(`${baseUrl}/containers/json?all=true`)
    if (!res.ok) return []
    const containers = (await res.json()) as { Names: string[]; State: string }[]
    return containers.map((c) => ({
      name: c.Names[0]?.replace(/^\//, '') ?? 'unknown',
      status: c.State === 'running' ? 'healthy' : c.State === 'restarting' ? 'warning' : 'critical',
      detail: c.State,
    }))
  },
}
