/**
 * Phase 2 browser chaos — IndexedDB scenarios. The upload queue
 * (frontend/src/lib/upload-queue.ts) persists pending uploads in
 * IndexedDB. Tests assert that purging or partially purging this DB
 * leaves the app in a recoverable state.
 */
import { test, expect } from '../../fixtures/test';

test.describe('Browser chaos — IndexedDB', () => {
  test('IndexedDB cleared mid-session does not break navigation', async ({
    page,
    guest,
    signIn,
  }) => {
    const g = await guest('IdbPurge');
    await signIn(page, g);
    await page.goto('/feed');

    await page.evaluate(async () => {
      // Drop every IndexedDB database the app might use.
      const dbs = (await (indexedDB as any).databases?.()) ?? [];
      await Promise.all(
        dbs.map(
          ({ name }: { name: string }) =>
            new Promise<void>((resolve) => {
              const req = indexedDB.deleteDatabase(name);
              req.onsuccess = req.onerror = req.onblocked = () => resolve();
            })
        )
      );
    });

    await page.reload();
    await expect(page.getByRole('link', { name: 'Galerie' })).toBeVisible();
  });

  test('feed renders even if IndexedDB API is undefined', async ({ page, guest, signIn }) => {
    const g = await guest('IdbMissing');
    // Stub IndexedDB to undefined before navigation so the app loads without it.
    await page.addInitScript(() => {
      Object.defineProperty(window, 'indexedDB', { value: undefined, configurable: true });
    });
    await signIn(page, g);
    await page.goto('/feed');
    await expect(page.getByRole('link', { name: 'Galerie' })).toBeVisible();
  });
});
