import type { createAuthClient } from "better-auth/react"; import { authStoragePrefix } from "@/lib/accounts"; import { clearAuthStorage, GUEST_AUTH_STORAGE_PREFIX, prepareForAdditionalSignIn, } from "@/lib/auth-storage"; type AuthClient = ReturnType; type PerformAuthResetInput = { authClient: AuthClient; clearActiveAccount: () => Promise; activeAccountId?: string | null; refetchSession?: () => Promise; }; /** Sign out, wipe local auth storage, and return to guest mode for a clean sign-in screen. */ export async function performAuthReset({ authClient, clearActiveAccount, activeAccountId, refetchSession, }: PerformAuthResetInput): Promise { const accountPrefix = activeAccountId ? authStoragePrefix(activeAccountId) : null; try { await authClient.signOut(); } catch { // Continue clearing local state even when the server session is already gone. } if (accountPrefix) { await clearAuthStorage(accountPrefix); } await clearAuthStorage(GUEST_AUTH_STORAGE_PREFIX); await clearActiveAccount(); await refetchSession?.(); } /** * When the auth stack is shown, discard stale SecureStore sessions so sign-in starts clean. * Expired account sessions switch back to guest storage; orphaned guest copies are cleared. */ export async function prepareAuthScreenSession( authClient: AuthClient, activeAccountId: string | null, clearActiveAccount: () => Promise, ): Promise { const session = await authClient.getSession(); if (session.data?.user) return; if (activeAccountId) { await clearAuthStorage(authStoragePrefix(activeAccountId)); await clearActiveAccount(); } await prepareForAdditionalSignIn(); }