/**
 * Lê o Bearer token do sessionStorage de forma segura (SSR-safe).
 */
function getToken(): string | null {
  if (typeof window === 'undefined') return null
  return sessionStorage.getItem('adm_token')
}

/**
 * Monta os headers de autenticação injetando o Bearer token quando disponível.
 */
function authHeaders(extra?: HeadersInit): HeadersInit {
  const token = getToken()
  return {
    ...(extra ?? {}),
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  }
}

/**
 * Wrapper de fetch autenticado para mutações (POST, PUT, PATCH, DELETE).
 * Injeta automaticamente o Bearer token e Content-Type JSON.
 */
export async function apiFetch(url: string, options: RequestInit = {}): Promise<Response> {
  return fetch(url, {
    ...options,
    credentials: 'include',
    headers: authHeaders({
      'Content-Type': 'application/json',
      ...(options.headers ?? {}),
    }),
  })
}

/**
 * Fetcher padrão do SWR — retorna os dados como vieram da API.
 * Lança erro com .status para que o SWRConfig.onError possa filtrá-lo.
 * Retorna null em caso de 401 para que o SWR não substitua dados existentes.
 */
export async function fetcher(url: string) {
  const res = await fetch(url, { credentials: 'include', headers: authHeaders() })
  if (res.status === 401) {
    const err = new Error('Unauthorized') as any
    err.status = 401
    throw err
  }
  if (!res.ok) {
    const err = new Error(`HTTP ${res.status}`) as any
    err.status = res.status
    throw err
  }
  const data = await res.json()
  return data
}

/**
 * Fetcher que sempre garante retorno de array.
 * Usar quando o SWR default value é [].
 */
export async function arrayFetcher(url: string): Promise<any[]> {
  const res = await fetch(url, { credentials: 'include', headers: authHeaders() })
  if (res.status === 401) {
    const err = new Error('Unauthorized') as any
    err.status = 401
    throw err
  }
  if (!res.ok) return []
  const data = await res.json()
  return Array.isArray(data) ? data : (data?.data ?? [])
}
