import * as SecureStore from 'expo-secure-store'; import React, { createContext, useCallback, useContext, useEffect, useState } from 'react'; export const BASE = 'https://health.rehbock.xyz'; export const EP = { meta: `${BASE}/health-meta.json`, biomarkers: `${BASE}/api/health/v1/biomarkers`, draws: `${BASE}/api/health/v1/draws`, workouts: `${BASE}/api/health/v1/workouts`, sleepApi: `${BASE}/api/health/v1/sleep`, sleepCycle: `${BASE}/sleep-data.json`, dexa: `${BASE}/dexa-scans.json`, medStats: `${BASE}/api/meditation/v1/stats`, medSessions: `${BASE}/api/meditation/v1/sessions?limit=1000`, traits: `${BASE}/ancestry-traits.json`, fitbitSummary: `${BASE}/api/health/v1/fitbit/summary?days=30`, fitbitLatest: `${BASE}/api/health/v1/fitbit/latest`, } as const; export const FITBIT_SYNC_URL = `${BASE}/api/health/v1/fitbit/sync`; /* authenticated POST (fitbit sync) */ export async function postJson(url: string, body: unknown): Promise { if (!token) throw new Error(NO_TOKEN); const r = await fetch(url, { method: 'POST', headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); if (r.status === 401 || r.status === 403) throw new Error(BAD_TOKEN); if (!r.ok) throw new Error(`${url} → ${r.status}`); return r.json(); } export type EpKey = keyof typeof EP; const AUTH_KEY = 'hd.token'; export const NO_TOKEN = 'No API token — add one in Settings.'; export const BAD_TOKEN = 'API token rejected — check it in Settings.'; let token: string | null = null; async function authFetch(url: string): Promise { if (!token) throw new Error(NO_TOKEN); const r = await fetch(url, { headers: { Authorization: 'Bearer ' + token }, cache: 'no-store', }); if (r.status === 401 || r.status === 403) throw new Error(BAD_TOKEN); if (!r.ok) throw new Error(`${url} → ${r.status}`); return r.json(); } /* module-level promise cache, cleared on refresh/logout */ let cache: Partial>> = {}; export function load(key: EpKey): Promise { if (!cache[key]) cache[key] = authFetch(EP[key]).catch((e) => { delete cache[key]; throw e; }); return cache[key] as Promise; } export function clearCache() { cache = {}; } /* drop specific endpoints from the cache so the next load() refetches */ export function invalidate(...keys: EpKey[]) { for (const k of keys) delete cache[k]; } /* ---- auth context ---- */ interface AuthCtx { ready: boolean; /** an API token is stored (it may still be rejected by the server) */ hasToken: boolean; /** verify against the server, then store; false = server rejected it */ saveToken: (t: string) => Promise; clearToken: () => void; } const Ctx = createContext({ ready: false, hasToken: false, saveToken: async () => false, clearToken: () => {}, }); export const useAuth = () => useContext(Ctx); export function AuthProvider({ children }: { children: React.ReactNode }) { const [ready, setReady] = useState(false); const [hasToken, setHasToken] = useState(false); useEffect(() => { SecureStore.getItemAsync(AUTH_KEY) .then((t) => { if (t) { token = t; setHasToken(true); } }) .catch(() => {}) .finally(() => setReady(true)); }, []); const clearToken = useCallback(() => { token = null; clearCache(); SecureStore.deleteItemAsync(AUTH_KEY).catch(() => {}); setHasToken(false); }, []); const saveToken = useCallback(async (raw: string) => { const t = raw.trim(); const r = await fetch(EP.meta, { headers: { Authorization: 'Bearer ' + t }, cache: 'no-store', }); if (!r.ok) return false; token = t; clearCache(); await SecureStore.setItemAsync(AUTH_KEY, t); setHasToken(true); return true; }, []); return {children}; }