import * as SecureStore from 'expo-secure-store'
import { createMMKV } from 'react-native-mmkv'
import { appStorage, userStorage } from './storage'

const SCHEMA_FLAG = 'schema.v1.cleared'

// Keys that existed in the single-account schema. Listed explicitly so the
// wipe is auditable; missing keys are fine.
const LEGACY_SECURE_KEYS = [
  'secure.access_token',
  'secure.refresh_token',
  'secure.client_id',
  'secure.client_secret',
] as const

const LEGACY_APP_KEYS = [
  'app.instance',
  'app.name',
  'app.redirect_uri',
  'app.token_created_at',
  'app.expires_in',
  // Mastodon Pass 3 Phase 1 §2.4 — the composer draft used to be a single
  // device-global blob. The new shape is `ui.composer.draft.v1.<accountId>`
  // (see src/lib/media/draft.ts). Drop the legacy key on first launch so a
  // dev whose device still carries one doesn't have an unreachable orphan
  // sitting on disk forever. `userStorage.clearAll()` does not cover this:
  // the draft lives in `appStorage`, which we deliberately preserve.
  'ui.composer.draft.v1',
] as const

/**
 * One-shot wipe of legacy single-account state on first launch of the
 * multi-account build. Halflight has not been deployed publicly, so the
 * dev team's existing local installs are acceptable casualties — they will
 * re-login once.
 *
 * Runs synchronously at module load alongside `migrateStorageIfNeeded()`
 * and `cleanupStaleThemeIfNeeded()`. Gated by `schema.v1.cleared` so it
 * fires exactly once.
 *
 * Deliberately preserves `ui.*` global preferences (theme, hideCaptions,
 * etc.) — those survive the rewire so the dev keeps their settings. The
 * per-account UI prefs (forceSensitive, requireSelfAltText, homeLens) will
 * pick up the global default the next time an account is added (see plan
 * §3.4 / §10).
 */
export function bootCleanupV1(): void {
  if (appStorage.getBoolean(SCHEMA_FLAG)) return

  // Legacy keychain entries — best-effort delete. SecItem returns
  // errSecItemNotFound for missing keys and expo-secure-store swallows it,
  // but wrap in try/catch defensively in case underlying behaviour shifts.
  for (const key of LEGACY_SECURE_KEYS) {
    try {
      // Fire-and-forget: synchronous boot cleanup, async deletes finish on
      // their own. The schema flag below ensures we never re-enter.
      SecureStore.deleteItemAsync(key).catch(() => {})
    } catch {
      // ignore
    }
  }

  // Legacy MMKV. No per-account keys exist yet (Phase 1 hasn't shipped a
  // working app), so a full clearAll on userStorage is safe.
  userStorage.clearAll()

  for (const key of LEGACY_APP_KEYS) {
    appStorage.remove(key)
  }

  // The persisted React Query cache pre-dates account-scoped query keys —
  // its entries would be unreachable under the new factory and would sit on
  // disk wasting space until the 12 h TTL expires. Wipe it.
  try {
    const queryCache = createMMKV({ id: 'react-query-cache' })
    queryCache.clearAll()
  } catch {
    // ignore — first launch may not have created this MMKV instance yet.
  }

  appStorage.set(SCHEMA_FLAG, true)
}
