export class ApiError extends Error {
  status: number
  constructor(message: string, status: number) {
    super(message)
    this.status = status
  }
}

let csrfToken = ''

export function setCsrf(token: string) {
  csrfToken = token
}

export function getCsrf() {
  return csrfToken
}

let unauthorizedHandler: (() => void) | null = null
let sessionRefresher: (() => Promise<void>) | null = null

/** Called once per expired-session response so the shell can show the login. */
export function setUnauthorizedHandler(fn: () => void) {
  unauthorizedHandler = fn
}

/** Used to fetch a fresh CSRF token before retrying a rejected request. */
export function setSessionRefresher(fn: () => Promise<void>) {
  sessionRefresher = fn
}

/** Lets streaming code reuse the shell's expired-session handling. */
export function triggerUnauthorized() {
  unauthorizedHandler?.()
}

interface Envelope<T> {
  code: number
  msg: string
  data: T
}

async function request<T>(
  method: string,
  path: string,
  body?: unknown,
  allowRetry = true,
): Promise<T> {
  const headers: Record<string, string> = {}
  if (body !== undefined) headers['Content-Type'] = 'application/json'
  if (method !== 'GET') headers['X-CSRF-Token'] = csrfToken

  let res: Response
  try {
    res = await fetch(path, {
      method,
      headers,
      credentials: 'same-origin',
      body: body === undefined ? undefined : JSON.stringify(body),
    })
  } catch {
    throw new ApiError('无法连接面板，请检查网络或服务状态', 0)
  }

  let env: Envelope<T> | null = null
  try {
    env = (await res.json()) as Envelope<T>
  } catch {
    env = null
  }

  if (res.status === 401) {
    unauthorizedHandler?.()
    throw new ApiError(env?.msg || '登录已过期，请重新登录', 401)
  }

  // The session cookie may outlive a server-side restart of the CSRF secret;
  // one silent refresh avoids a confusing "请刷新页面" toast.
  if (
    res.status === 403 &&
    allowRetry &&
    sessionRefresher &&
    /CSRF/i.test(env?.msg ?? '')
  ) {
    try {
      await sessionRefresher()
      return await request<T>(method, path, body, false)
    } catch {
      /* fall through to the original error */
    }
  }

  if (!env) {
    throw new ApiError(`服务器返回异常 (HTTP ${res.status})`, res.status)
  }
  if (!res.ok || env.code !== 0) {
    throw new ApiError(env.msg || `请求失败 (HTTP ${res.status})`, res.status)
  }
  return env.data
}

export const api = {
  get: <T>(path: string) => request<T>('GET', path),
  post: <T>(path: string, body?: unknown) => request<T>('POST', path, body ?? {}),
  put: <T>(path: string, body?: unknown) => request<T>('PUT', path, body ?? {}),
  patch: <T>(path: string, body?: unknown) => request<T>('PATCH', path, body ?? {}),
  del: <T>(path: string) => request<T>('DELETE', path),
}
