import { createAuthClient } from 'better-auth/react'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { getApiBaseUrl } from './api-url'

const apiUrl = getApiBaseUrl()

export const authClient = createAuthClient({
  baseURL: apiUrl,
  plugins: [],
  fetchOptions: {
    customFetchImpl: async (url, options) => {
      const token = await AsyncStorage.getItem('better-auth-session')
      const headers = new Headers((options?.headers as HeadersInit) ?? {})
      headers.set('origin', apiUrl)
      if (token) {
        headers.set('cookie', `better-auth.session_token=${token}`)
      }
      return fetch(url, { ...options, headers })
    },
  },
})
