const PURGED_FLAG = 'chitai:locations-purged';

/** Keys the epub.js reader wrote: `${bookId}-locations`. */
const LEGACY_KEY = /^\d+-locations$/;

/**
 * Drops the epub.js locations cache, once per browser.
 *
 * foliate computes progress from section byte sizes at open time, so there is no
 * locations pre-pass and nothing to cache. The old entries are not small — a
 * few hundred KB of JSON per long book against a 5–10 MB origin quota — and a
 * heavy reader sitting near the cap would make the new settings write throw
 * QuotaExceededError.
 *
 * Removable once deployments have had a release to run it; see TODO.md.
 */
export function purgeLegacyLocationCache() {
	try {
		if (localStorage.getItem(PURGED_FLAG)) return;

		for (const key of Object.keys(localStorage)) {
			if (LEGACY_KEY.test(key)) localStorage.removeItem(key);
		}

		localStorage.setItem(PURGED_FLAG, '1');
	} catch (error) {
		console.warn('Could not purge the legacy locations cache', error);
	}
}
