import { apiBase } from '../config'

const prefix = () => (apiBase ? `${apiBase}/api` : '/api')

/** 与 /web/routes 返回的 site_id 一致，拉取单页时附带，避免多站点下错站 */
let cachedWebSiteId = ''

export function getCachedWebSiteId() {
  return cachedWebSiteId
}

export async function fetchWebRoutes() {
  let url = `${prefix()}/web/routes`
  const sid = new URLSearchParams(window.location.search).get('site_id')
  if (sid) url += `?site_id=${encodeURIComponent(sid)}`
  const res = await fetch(url)
  if (!res.ok) {
    cachedWebSiteId = ''
    return { site_id: '', routes: [] }
  }
  const data = await res.json()
  cachedWebSiteId = data.site_id || ''
  return data
}

export async function fetchWebPageByPath(path) {
  const q = new URLSearchParams({ path: path || '/' })
  const fromQs = new URLSearchParams(window.location.search).get('site_id')
  const sid = cachedWebSiteId || fromQs
  if (sid) q.set('site_id', sid)
  const res = await fetch(`${prefix()}/web/page?${q}`)
  if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || '加载失败')
  return res.json()
}
