import { environment } from '../environments/environment'; import { akashicFetch } from '../config/clientManifest'; // Asks the server for an org-less account and home Patient. Pre-session and unauthenticated, so a plain // fetch: there is no token to attach. export type NeutralAccountOutcome = // The server answers 202 whether or not the address already had an account. | { outcome: 'accepted' } | { outcome: 'refused'; message: string } // Offline, DNS and CORS failures: none of them is a refusal. | { outcome: 'unreachable' }; const FALLBACK_REFUSAL = 'That account could not be created.'; export const requestNeutralAccount = async ( // `invitation`: the signup happens mid-invitation, so the account mail must not link elsewhere. request: { email: string; firstname: string; lastname: string; birthdate?: string; for?: 'invitation' }, ): Promise => { let response: Response; try { response = await akashicFetch(`${environment.fhirIdentityApi}/account`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: request.email.trim().toLowerCase(), firstname: request.firstname.trim(), lastname: request.lastname.trim(), as: 'patient', ...(request.birthdate ? { birthdate: request.birthdate } : {}), ...(request.for ? { for: request.for } : {}), }), }); } catch { return { outcome: 'unreachable' }; } if (response.ok) return { outcome: 'accepted' }; // The server's own sentence where it wrote one (an incomplete form, the daily ceiling). try { const body: unknown = await response.json(); const message = (body as { message?: unknown } | null)?.message; return { outcome: 'refused', message: typeof message === 'string' && message ? message : FALLBACK_REFUSAL }; } catch { return { outcome: 'refused', message: FALLBACK_REFUSAL }; } };