/**
 * store_versions.ts
 *
 * Single source of truth for persisted store schema versions.
 *
 * HOW IT WORKS:
 * This file is imported at the top of ae_stores.ts and ae_events_stores.ts.
 * ES modules resolve imports before running the importing module's body,
 * so the version check + localStorage wipe here runs BEFORE persisted() is
 * called — meaning stale data is cleared before svelte-persisted-store
 * can hydrate from it.
 *
 * HOW TO USE:
 * When a store schema changes in a breaking way (type change, required
 * restructure, field rename that code depends on), bump the relevant version
 * by 1. Any client with an older version will have that store silently wiped
 * on next page load. They re-initialize from the new defaults.
 *
 * WHAT COUNTS AS BREAKING:
 *   - Changing a field's type (e.g. string → object, or null → required object)
 *   - Renaming a field that code reads directly (not just a display label)
 *   - Restructuring a nested object that breaks existing property access
 *   DOES NOT require a bump:
 *   - Adding a new optional field (svelte-persisted-store deep-merges defaults)
 *   - Removing a field (old value is ignored, no error)
 *   - Changing a default value when the stored value being stale is acceptable
 *
 * localStorage keys:
 *   'ae_loc'        → AE_LOC_VERSION
 *   'ae_events_loc' → AE_EVENTS_LOC_VERSION
 */

export const AE_LOC_VERSION = 1;
export const AE_EVENTS_LOC_VERSION = 1;

// Version check side-effect: runs on import, before any persisted() call.
// Guards typeof localStorage for safety (SSR environments, test runners).
if (typeof localStorage !== 'undefined') {
    _check_and_wipe('ae_loc', AE_LOC_VERSION);
    _check_and_wipe('ae_events_loc', AE_EVENTS_LOC_VERSION);
}

function _check_and_wipe(key: string, expected_version: number): void {
    try {
        const raw = localStorage.getItem(key);
        if (!raw) return; // No stored value — nothing to wipe.

        const parsed = JSON.parse(raw);
        if (parsed?.__version !== expected_version) {
            localStorage.removeItem(key);
            console.info(
                `[store_versions] '${key}' wiped — schema v${parsed?.__version ?? 'none'} → v${expected_version}`
            );
        }
    } catch {
        // Corrupt JSON — wipe unconditionally.
        localStorage.removeItem(key);
        console.warn(`[store_versions] '${key}' wiped — corrupt JSON in localStorage`);
    }
}
