import authFetch from './authFetch.js'; const API_ROOT = (import.meta?.env?.VITE_API_BASE || '').replace(/\/+$/, ''); const DRAFT_URL = `${API_ROOT}/api/premium/onboarding/draft`; export async function loadDraft() { const res = await authFetch(DRAFT_URL); if (!res) return null; // session expired if (res.status === 404) return null; if (!res.ok) throw new Error(`loadDraft ${res.status}`); return res.json(); // null or { id, step, data } } /** * saveDraft(input) * Accepts either: * - { id, step, data } // full envelope * - { id, step, careerData?, financialData?, collegeData? } // partial sections * Merges partials with the current server draft to avoid clobbering. */ export async function saveDraft(input = {}) { // Normalize inputs let { id = null, step = 0, data } = input; // If caller passed sections (careerData / financialData / collegeData) instead of a 'data' envelope, // merge them into the existing server draft so we don't drop other sections. if (data == null) { // Load existing draft (may be null/404 for first-time) let existing = null; try { existing = await loadDraft(); } catch (_) {} const existingData = (existing && existing.data) || {}; const has = (k) => Object.prototype.hasOwnProperty.call(input, k); const patch = {}; if (has('careerData')) patch.careerData = input.careerData; if (has('financialData')) patch.financialData = input.financialData; if (has('collegeData')) patch.collegeData = input.collegeData; data = { ...existingData, ...patch }; // Prefer caller's id/step when provided; otherwise reuse existing if (id == null && existing?.id != null) id = existing.id; if (step == null && existing?.step != null) step = existing.step; } const res = await authFetch(DRAFT_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id, step, data }), }); if (!res) return null; if (!res.ok) throw new Error(`saveDraft ${res.status}`); return res.json(); // { id, step } } export async function clearDraft() { const res = await authFetch(DRAFT_URL, { method: 'DELETE' }); if (!res) return false; if (!res.ok) throw new Error(`clearDraft ${res.status}`); return true; // server returns { ok: true } }