export const useApi = () => {
  // Apenas o config fica no topo
  const config = useRuntimeConfig()
  const baseURL = config.public.apiBase

  const getHeaders = (): Record<string, string> => {
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    }
    
    const authStore = useAuthStore()
    
    if (authStore.isAuthenticated) {
      headers['Authorization'] = `Bearer ${authStore.getToken}`
    }

    return headers
  }

  const handleError = async (response: Response) => {
    const authStore = useAuthStore()

    if (response.status === 401) {
      authStore.clearAuth()
      
      await navigateTo('/admin/login') 
      
      throw new Error('Não autorizado')
    }
    
    const data = await response.json().catch(() => ({}))
    const message = data.message || data.error || `Erro ${response.status}`
    throw new Error(message)
  }

  const get = async <T = any>(path: string, params?: Record<string, any>): Promise<T> => {
    const url = new URL(`${baseURL}${path}`)
    if (params) {
      Object.entries(params).forEach(([k, v]) => {
        if (v !== undefined && v !== null && v !== '') {
          url.searchParams.set(k, String(v))
        }
      })
    }
    const response = await fetch(url.toString(), { headers: getHeaders() })
    if (!response.ok) await handleError(response)
    return response.json()
  }

  const post = async <T = any>(path: string, body?: any): Promise<T> => {
    const response = await fetch(`${baseURL}${path}`, {
      method: 'POST',
      headers: getHeaders(),
      body: body ? JSON.stringify(body) : undefined,
    })
    if (!response.ok) await handleError(response)
    return response.json()
  }

  const put = async <T = any>(path: string, body?: any): Promise<T> => {
    const response = await fetch(`${baseURL}${path}`, {
      method: 'PUT',
      headers: getHeaders(),
      body: body ? JSON.stringify(body) : undefined,
    })
    if (!response.ok) await handleError(response)
    return response.json()
  }

  const del = async <T = any>(path: string): Promise<T> => {
    const response = await fetch(`${baseURL}${path}`, {
      method: 'DELETE',
      headers: getHeaders(),
    })
    if (!response.ok) await handleError(response)
    return response.json()
  }

  return { get, post, put, del }
}