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

interface CloudflareZoneResponse {
  success: boolean
  result?: { name: string; status: string }
  errors?: { message: string }[]
}

export const cloudflare: IntegrationAdapter = {
  async testConnection(config, secrets) {
    const zoneId = config.zoneId
    const apiKey = secrets.apiKey
    if (!zoneId) return { ok: false, message: 'Missing zone ID' }
    if (!apiKey) return { ok: false, message: 'Missing API token' }
    try {
      const res = await fetch(`https://api.cloudflare.com/client/v4/zones/${zoneId}`, {
        headers: { Authorization: `Bearer ${apiKey}` },
      })
      if (!res.ok) return { ok: false, message: `HTTP ${res.status}` }
      const body = (await res.json()) as CloudflareZoneResponse
      if (!body.success) return { ok: false, message: body.errors?.[0]?.message ?? 'Request failed' }
      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 zoneId = config.zoneId
    const apiKey = secrets.apiKey
    if (!zoneId || !apiKey) return []
    const res = await fetch(`https://api.cloudflare.com/client/v4/zones/${zoneId}`, {
      headers: { Authorization: `Bearer ${apiKey}` },
    })
    if (!res.ok) return []
    const body = (await res.json()) as CloudflareZoneResponse
    if (!body.success || !body.result) return []
    return [
      {
        name: body.result.name,
        status: body.result.status === 'active' ? 'healthy' : body.result.status === 'pending' || body.result.status === 'initializing' ? 'warning' : 'critical',
        detail: `Zone status: ${body.result.status}`,
      },
    ]
  },
}
