/**
 * Phase 7 of the magnotia -> lumotia rebrand cascade. Persisted UI state
 * survives the rename via one-shot key migrations run at module-load
 * inside the stores that own each key.
 *
 * `migrateLocalStorageKey` is idempotent and crash-safe:
 *  - If the new key already exists, the old (magnotia) key is removed
 *    silently — the new (lumotia) value is authoritative; the legacy
 *    (magnotia) key is removed.
 *  - If only the old key exists, its value is copied to the new key and
 *    the old key is removed.
 *  - If neither exists, this is a no-op.
 */

const STORAGE_NS = "lumotia-rebrand-migration";

export function migrateLocalStorageKey(oldKey: string, newKey: string): void {
  if (typeof localStorage === "undefined") return;
  try {
    const newValue = localStorage.getItem(newKey);
    if (newValue !== null) {
      if (localStorage.getItem(oldKey) !== null) {
        localStorage.removeItem(oldKey);
      }
      return;
    }
    const oldValue = localStorage.getItem(oldKey);
    if (oldValue === null) return;
    localStorage.setItem(newKey, oldValue);
    localStorage.removeItem(oldKey);
  } catch (err) {
    // Quota / disabled-storage / DOMException — silently no-op. The store
    // will fall back to the old key on next read (or fail there with a
    // visible error). Logging is intentionally silent to avoid polluting
    // dev-console output on every page in the multi-window flow.
    void err;
  }
}

/**
 * Run a batch of migrations. Used by stores that own multiple keys.
 */
export function migrateLocalStorageKeys(pairs: Array<[string, string]>): void {
  for (const [oldKey, newKey] of pairs) {
    migrateLocalStorageKey(oldKey, newKey);
  }
}

void STORAGE_NS;
