import { ensureAuth, getCookie } from './geelib-auth.mjs'

const DEFAULT_BASE_URL = 'https://geelib.qihoo.net'

/** 解析 GeeLib API 根地址；未配置或占位符未展开时使用官方默认域名 */
function resolveBaseUrl() {
  const raw = process.env.GEELIB_BASE_URL?.trim() ?? ''
  if (raw.length === 0 || raw.includes('${')) {
    return DEFAULT_BASE_URL
  }
  return raw.replace(/\/$/, '')
}

function buildHeaders() {
  const baseUrl = resolveBaseUrl()
  return {
    Cookie: getCookie(),
    'Content-Type': 'application/json',
    Accept: 'application/json, text/plain, */*',
    'X-Requested-With': 'XMLHttpRequest',
    Referer: `${baseUrl}/geelib/`,
    'User-Agent':
      'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
  }
}

async function request(fn) {
  await ensureAuth()
  let resp = await fn()
  if (resp.status === 401 || resp.status === 403) {
    await ensureAuth()
    resp = await fn()
  }
  if (!resp.ok) {
    throw new Error(`HTTP ${resp.status} ${resp.statusText} — ${resp.url}`)
  }
  return resp.json()
}

export async function geelibGet(path, params) {
  const url = new URL(path, resolveBaseUrl())
  if (params) {
    for (const [k, v] of Object.entries(params)) {
      if (v !== undefined) {
        url.searchParams.set(k, String(v))
      }
    }
  }
  return request(() =>
    fetch(url.toString(), { method: 'GET', headers: buildHeaders() }),
  )
}

export async function geelibPost(path, body) {
  const url = new URL(path, resolveBaseUrl())
  return request(() =>
    fetch(url.toString(), {
      method: 'POST',
      headers: buildHeaders(),
      body: body !== undefined ? JSON.stringify(body) : undefined,
    }),
  )
}
