import { hostApiFetch } from '@/lib/host-api'; import { normalizeUserSyncBootstrap, toUserSyncPartner, toUserSyncPreferences, type UserSyncBootstrap, type UserSyncPartner, type UserSyncPreferences, } from '../../shared/user-sync'; type UserSyncBootstrapResponse = { success: boolean; error?: string; bootstrap?: unknown; }; function requireBootstrapResponse(response: UserSyncBootstrapResponse, fallback: string): UserSyncBootstrap { if (!response.success || !response.bootstrap) { throw new Error(response.error || fallback); } return normalizeUserSyncBootstrap(response.bootstrap); } export async function fetchUserSyncBootstrap(accessToken: string): Promise { const response = await hostApiFetch('/api/user-sync/bootstrap', { headers: { 'x-niancode-access-token': accessToken }, }); return requireBootstrapResponse(response, 'Failed to fetch user sync bootstrap'); } export async function pushUserSyncPreferences( accessToken: string, preferences: UserSyncPreferences, ): Promise { const response = await hostApiFetch('/api/user-sync/preferences', { method: 'PUT', headers: { 'x-niancode-access-token': accessToken }, body: JSON.stringify(toUserSyncPreferences(preferences)), }); return requireBootstrapResponse(response, 'Failed to push user preferences'); } export async function pushUserSyncPartner( accessToken: string, partner: UserSyncPartner, ): Promise { const response = await hostApiFetch('/api/user-sync/partners', { method: 'POST', headers: { 'x-niancode-access-token': accessToken }, body: JSON.stringify(toUserSyncPartner(partner)), }); return requireBootstrapResponse(response, 'Failed to push user partner'); }