const API_BASE = 'https://api.resos.com/v1'

async function getCredentials() {
  const url = `${process.env.SETTINGS_URL}/settings/api/internal/integration/resos`
  const res = await fetch(url, {
    headers: { Authorization: `Bearer ${process.env.SETTINGS_SECRET}` },
    signal: AbortSignal.timeout(5000),
  })
  if (!res.ok) throw new Error(`Settings service returned ${res.status} fetching ResOS credentials`)
  const s = await res.json()
  return { apiKey: s.api_key || '' }
}

export async function callApi(path, params = {}) {
  const creds = await getCredentials()
  if (!creds.apiKey) throw new Error('ResOS API key not configured — set it in Settings → Integrations')

  const url = new URL(`${API_BASE}/${path}`)
  for (const [k, v] of Object.entries(params)) {
    if (v !== undefined && v !== null) url.searchParams.set(k, String(v))
  }

  const auth = Buffer.from(`${creds.apiKey}:`).toString('base64')
  const res = await fetch(url.toString(), {
    headers: { Authorization: `Basic ${auth}`, Accept: 'application/json' },
    signal: AbortSignal.timeout(15000),
  })
  if (!res.ok) {
    const text = await res.text().catch(() => '')
    throw new Error(`ResOS API ${res.status}: ${text.slice(0, 200)}`)
  }
  return await res.json()
}
