import { appStorage } from 'src/state/storage'

/**
 * Per-account draft MMKV key shape. Sunk into this leaf module so neither
 * `accountStore.ts` (registry teardown caller) nor `media/draft.ts`
 * (draft load/save caller) needs the other — the require-cycle they
 * formed previously was benign today but a latent footgun on any
 * Hermes/Metro bundling-order change.
 *
 * The legacy device-global key `ui.composer.draft.v1` (no accountId
 * suffix) is wiped on first launch by `bootCleanupV1`.
 */
export const DRAFT_KEY_PREFIX = 'ui.composer.draft.v1.'

export const draftKey = (accountId: string) => `${DRAFT_KEY_PREFIX}${accountId}`

/**
 * Drop the saved draft for a specific account. Used by future surgical-
 * drop paths (admin-mode reset, post-sign-out cleanup if we ever stop
 * preserving drafts across re-sign-in).
 */
export function clearDraftFor(accountId: string): void {
  appStorage.remove(draftKey(accountId))
}

/**
 * Drop every per-account draft on the device. Used by AccountStore
 * .clearAll (Sign out of all accounts). Walks `appStorage.getAllKeys()`
 * because the registry has already been wiped by the time this runs
 * and accountIds are no longer enumerable from the registry side.
 */
export function clearAllDrafts(): void {
  for (const k of appStorage.getAllKeys()) {
    if (k.startsWith(DRAFT_KEY_PREFIX)) appStorage.remove(k)
  }
}
