export default defineNuxtPlugin(() => {
  const safeMethods = new Set(['GET', 'HEAD', 'OPTIONS'])

  globalThis.$fetch = globalThis.$fetch.create({
    onRequest({ options }) {
      const method = (options.method || 'GET').toUpperCase()
      if (safeMethods.has(method)) return

      // Read CSRF token from cookie
      const csrfToken = useCookie('csrf-token').value
      if (csrfToken) {
        options.headers = options.headers || {}
        if (options.headers instanceof Headers) {
          options.headers.set('x-csrf-token', csrfToken)
        } else if (Array.isArray(options.headers)) {
          options.headers.push(['x-csrf-token', csrfToken])
        } else {
          options.headers['x-csrf-token'] = csrfToken
        }
      }
    }
  })
})
