const SETUP_API_BASE = '/__setup'

function formatValidationErrors(detail) {
  if (!Array.isArray(detail)) {
    return ''
  }

  return detail
    .map((item) => {
      const field = Array.isArray(item.loc) ? item.loc[item.loc.length - 1] : 'field'
      return `${field}: ${item.msg}`
    })
    .join('\n')
}

async function request(path, options = {}) {
  let response

  try {
    response = await fetch(`${SETUP_API_BASE}${path}`, {
      headers: {
        'Content-Type': 'application/json',
        ...(options.headers || {})
      },
      ...options
    })
  } catch {
    throw new Error('无法连接初始化服务，请确认本地配置桥已启动。')
  }

  let data = null

  try {
    data = await response.json()
  } catch {
    data = null
  }

  if (!response.ok) {
    const validationMessage = formatValidationErrors(data?.detail)
    const message = validationMessage || data?.detail || '初始化请求失败，请稍后重试。'
    throw new Error(message)
  }

  return data
}

export function fetchBootstrapState() {
  return request('/bootstrap')
}

export function saveBootstrapConfig(payload) {
  return request('/bootstrap', {
    method: 'POST',
    body: JSON.stringify(payload)
  })
}

export function startBootstrapBackend() {
  return request('/bootstrap/backend', {
    method: 'POST'
  })
}

export function fetchBootstrapBackendStatus() {
  return request('/bootstrap/backend')
}

export function testBootstrapRuntime(payload) {
  return request('/bootstrap/runtime', {
    method: 'PUT',
    body: JSON.stringify(payload)
  })
}

export function testBootstrapDatabase(payload) {
  return request('/bootstrap/database', {
    method: 'PUT',
    body: JSON.stringify(payload)
  })
}

export function loginBootstrapAdmin(payload) {
  return request('/auth/login', {
    method: 'POST',
    body: JSON.stringify(payload)
  })
}
