import type { FetchOptions } from 'ofetch' /** * Wrapper para chamadas autenticadas ao core-api via BFF proxy. * * - Todas as requests passam por `/api/proxy/**` (que injeta Bearer + tenant headers no server) * - Headers CSRF (`X-Requested-With: fetch`) sempre injetados — exigido pelo middleware do BFF em mutating methods * * Uso típico: * const api = useApi() * const debitos = await api.get('portal/contribuinte/debitos') * const novo = await api.post('portal/contribuinte/debitos', payload) */ export function useApi() { function buildUrl(path: string): string { const clean = path.startsWith('/') ? path : `/${path}` return `/api/proxy${clean}` } async function request(path: string, options: FetchOptions = {}): Promise { try { return await $fetch(buildUrl(path), { ...options, headers: { 'X-Requested-With': 'fetch', ...(options.headers ?? {}), }, }) } catch (err: unknown) { if (import.meta.dev) { const e = err as { status?: number; data?: unknown } console.error(`[api] ${(options.method ?? 'GET').toUpperCase()} ${path} → ${e.status}`, e.data) } throw err } } return { request, get: (path: string, opts?: FetchOptions) => request(path, { ...opts, method: 'GET' }), post: (path: string, body?: unknown, opts?: FetchOptions) => request(path, { ...opts, method: 'POST', body }), put: (path: string, body?: unknown, opts?: FetchOptions) => request(path, { ...opts, method: 'PUT', body }), patch: (path: string, body?: unknown, opts?: FetchOptions) => request(path, { ...opts, method: 'PATCH', body }), delete: (path: string, opts?: FetchOptions) => request(path, { ...opts, method: 'DELETE' }), } }