import { test as base, BrowserContext } from '@playwright/test';

type OfflineFixture = {
    goOffline: (context: BrowserContext) => Promise<void>;
    goOnline: (context: BrowserContext) => Promise<void>;
};

export const test = base.extend<{ offlineControl: OfflineFixture }>({
    offlineControl: async ({ }, use) => {
        const offlineFixture = {
            goOffline: async (context: BrowserContext) => {
                await context.setOffline(true);
                for (const page of context.pages()) {
                    await page.evaluate(() => window.dispatchEvent(new Event('offline'))).catch(() => { });
                }
            },
            goOnline: async (context: BrowserContext) => {
                await context.setOffline(false);
                for (const page of context.pages()) {
                    await page.evaluate(() => window.dispatchEvent(new Event('online'))).catch(() => { });
                }
            },
        };

        await use(offlineFixture);
    },
});
