/**
 * Fetch 全局拦截器
 * 
 * 1. 请求拦截：自动为非 GET 请求添加 CSRF token
 * 2. 响应拦截：处理 401错误，自动退出登录
 */

import { handleSessionExpired } from './handleSessionExpired'

const originalFetch = window.fetch

window.fetch = async function(...args: Parameters<typeof fetch>): Promise<Response> {
  const [url, options = {}] = args
  const method = options.method?.toUpperCase() || 'GET'
  
  if (method !== 'GET') {
    const csrfToken = (window as any).jingrow?.csrf_token
    
    if (csrfToken) {
      const headers = new Headers(options.headers)
      headers.set('X-Jingrow-CSRF-Token', csrfToken)
      options.headers = headers
    }
  }
  
  const response = await originalFetch(url, options)
  
  if (response.status === 401) {
    await handleSessionExpired(response.status)
  }
  
  return response
}

export { originalFetch }

