/**
 * Helpers for inspecting and manipulating browser storage from Playwright.
 * Centralised here so the storage-key strings match auth.ts in one place.
 */
import type { Page } from '@playwright/test';

export const STORAGE_KEYS = {
  jwt: 'eventsnap_jwt',
  pin: 'eventsnap_pin',
  userId: 'eventsnap_user_id',
  displayName: 'eventsnap_display_name',
  guideSeen: 'eventsnap_guide_seen',
} as const;

export async function readStorage(page: Page) {
  return page.evaluate((keys) => {
    const out: Record<string, string | null> = {};
    for (const [name, key] of Object.entries(keys)) {
      out[name] = localStorage.getItem(key as string);
    }
    return out;
  }, STORAGE_KEYS);
}

export async function clearLocalStorage(page: Page) {
  if (page.url() === 'about:blank') await page.goto('/');
  await page.evaluate(() => localStorage.clear());
}

export async function clearSessionStorage(page: Page) {
  if (page.url() === 'about:blank') await page.goto('/');
  await page.evaluate(() => sessionStorage.clear());
}

export async function clearAllStorage(page: Page) {
  // localStorage is only accessible on a real origin — about:blank throws SecurityError.
  // Navigate to the app origin first if we're on the blank starting page.
  if (page.url() === 'about:blank') {
    await page.goto('/');
  }
  await page.evaluate(() => {
    localStorage.clear();
    sessionStorage.clear();
  });
  await page.context().clearCookies();
}
