/**
 * Wipes EVERY piece of user-specific data the app has stashed on the
 * device — Xtream/M3U playlists, the active-profile breadcrumb,
 * favorites, ad-free state, the proxy toggle, the native "last played"
 * channel, ALL localStorage keys, ALL IndexedDB tables, and (on
 * Android) the Capacitor Preferences store + WebView cache — so the
 * next user signing in on the same device starts with a completely
 * clean slate.
 *
 * What we DELIBERATELY keep (re-seeded after the wipe):
 *   • `nadiplay_lang`        — language preference (UX, not PII)
 *   • `nadiplay_lang_chosen` — "user already picked a language" flag
 *   • `nadiplay_device_id`   — device identifier (used by the backend
 *                              for per-device seat counts; must
 *                              persist across logouts so the same
 *                              device keeps the same seat)
 *
 * Everything else is destroyed. This includes Xtream server URLs,
 * usernames, passwords, MAC addresses, trial caches, FCM tokens,
 * managed-profile breadcrumbs, sync timestamps, resume-playback
 * positions, last-played channel — basically every PII or
 * session-bound value.
 *
 * BUG FIX (2026-01) — "Clear Cache on logout": the previous
 * implementation used an allow-list of explicit keys, which was
 * brittle (new feature → new key → leak on logout). The new
 * implementation switches to a deny-list of keys-to-preserve and
 * nukes everything else with `localStorage.clear()` + IndexedDB
 * deletion + native bridge cleanup. Safe to fire-and-forget from
 * a synchronous onClick.
 */
import { nadiDb } from "@/lib/nadiDb";
import { NativePlayer, isNativeApp } from "@/native/nativePlayer";

/** localStorage keys to PRESERVE across the wipe. Everything else
 *  in localStorage is destroyed. Keep this list minimal — only
 *  UX-friendly device-scoped (non-PII) flags belong here. */
const PRESERVE_LS_KEYS: readonly string[] = [
  "nadiplay_lang",          // i18n locale
  "nadiplay_lang_chosen",   // first-run language picker flag
  "nadiplay_device_id",     // stable per-device identifier
  "nadiplay_sn_debug",      // dev/debug flag
];

/**
 * Async because IndexedDB + the Capacitor bridge are both async. Safe
 * to fire-and-forget (`void clearUserData()`) from a sync onClick.
 *
 * Returns a Promise that resolves once every storage layer has been
 * cleared, so callers that need to chain (e.g. testing) can await it.
 */
export async function clearUserData(): Promise<void> {
  // ── 1. Snapshot the values we want to KEEP, before nuking. ────────
  const preserved: Record<string, string> = {};
  try {
    for (const k of PRESERVE_LS_KEYS) {
      const v = localStorage.getItem(k);
      if (v !== null) preserved[k] = v;
    }
  } catch (e) {
    console.warn("[clearUserData] localStorage snapshot failed:", e);
  }

  // ── 2. Wipe ALL localStorage in one shot. ─────────────────────────
  try {
    localStorage.clear();
  } catch (e) {
    console.warn("[clearUserData] localStorage.clear() failed:", e);
  }

  // ── 3. Restore preserved keys. ────────────────────────────────────
  try {
    for (const [k, v] of Object.entries(preserved)) {
      localStorage.setItem(k, v);
    }
  } catch (e) {
    console.warn("[clearUserData] preserve restore failed:", e);
  }

  // ── 4. Wipe sessionStorage too (some hooks cache here). ───────────
  try {
    sessionStorage.clear();
  } catch (e) {
    console.warn("[clearUserData] sessionStorage.clear() failed:", e);
  }

  // ── 5. Drop the IndexedDB profiles table (Xtream / M3U / Stalker). ─
  try {
    await nadiDb.profiles.clear();
  } catch (e) {
    console.warn("[clearUserData] nadiDb.profiles.clear failed:", e);
  }
  // Also delete any other tables Dexie might be tracking (future-proof
  // in case new feature work adds more tables to nadiDb).
  try {
    const tables = nadiDb.tables ?? [];
    for (const t of tables) {
      try { await t.clear(); } catch { /* table might be read-only */ }
    }
  } catch (e) {
    console.warn("[clearUserData] nadiDb full-table sweep failed:", e);
  }

  // ── 6. Wipe Android SharedPreferences via the native bridge. Some
  //       integrations (the PlaybackService's last-played blob, the
  //       AdMob plugin's cached consent state, channel-store snapshot)
  //       stash data here that survives a localStorage.clear(). The
  //       native side preserves PRESERVE_LS_KEYS so the device-id /
  //       language pick is not lost. ──────────────────────────────
  if (isNativeApp()) {
    try {
      // clearAppCache is a new bridge method added by NativePlayerPlugin
      // (BUG FIX 2026-01). Older builds of the native plugin will
      // reject the call with "method not implemented"; we swallow the
      // error because the localStorage + IndexedDB wipe above is
      // already sufficient for the web layer, and the next APK rebuild
      // ships the new method.
      if (typeof NativePlayer.clearAppCache === "function") {
        await NativePlayer.clearAppCache();
      }
    } catch (e) {
      console.warn("[clearUserData] NativePlayer.clearAppCache failed:", e);
    }
  }

  // ── 7. Tell the native side to forget the "last played" channel
  //       and any cached Xtream blob the foreground service stashed
  //       in SharedPreferences. ───────────────────────────────────
  if (isNativeApp()) {
    try {
      await NativePlayer.clearLastPlayed();
    } catch (e) {
      console.warn("[clearUserData] NativePlayer.clearLastPlayed failed:", e);
    }
  }
}
