export const useApi = () => { const config = useRuntimeConfig() // Use current domain for API calls (same subdomain routing) const getApiBaseUrl = () => { if (import.meta.client) { // In browser, use current hostname but with port 3000 for API const currentHost = window.location.hostname const protocol = window.location.protocol return `${protocol}//${currentHost}:3000` } // Fallback for SSR return config.public.apiBaseUrl } const getHeaders = () => { const headers: Record = { 'Content-Type': 'application/json', } // Add tenant ID from localStorage or state if (import.meta.client) { const tenantId = localStorage.getItem('tenantId') if (tenantId) { headers['x-tenant-id'] = tenantId } const token = localStorage.getItem('token') if (token) { headers['Authorization'] = `Bearer ${token}` } } return headers } const api = { async get(path: string) { const response = await fetch(`${getApiBaseUrl()}/api${path}`, { headers: getHeaders(), }) if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`) return response.json() }, async post(path: string, data: any) { const response = await fetch(`${getApiBaseUrl()}/api${path}`, { method: 'POST', headers: getHeaders(), body: JSON.stringify(data), }) if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`) return response.json() }, async put(path: string, data: any) { const response = await fetch(`${getApiBaseUrl()}/api${path}`, { method: 'PUT', headers: getHeaders(), body: JSON.stringify(data), }) if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`) return response.json() }, async delete(path: string) { const response = await fetch(`${getApiBaseUrl()}/api${path}`, { method: 'DELETE', headers: getHeaders(), }) if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`) return response.json() }, } return { api } }