import { test } from '@playwright/test';
import { siteConfig } from '../../config/siteConfig';
import { trackAnalytics } from '../../support/ga';

const smokeRoutes = [
    { name: 'home', path: siteConfig.routes.home },
    { name: 'product listing', path: siteConfig.routes.plp },
    { name: 'product detail', path: siteConfig.routes.pdp }
];

test.describe('Google Analytics instrumentation', () => {
    for (const route of smokeRoutes) {
        test(`${route.name} fires required events`, async ({ page }) => {
            const analytics = trackAnalytics(page, {
                ignorePreNavigationEvents: true,
                validateStructure: true,
                duplicateCheckMode: 'name-and-id'
            });

            try {
                const response = await page.goto(route.path);

                if (!response || response.status() === 404) {
                    test.skip(true, `Route ${route.path} returned 404`);
                    return;
                }

                await page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {
                    console.log('Network idle timeout - continuing with test');
                });

                await analytics.expectEvents(
                    siteConfig.analytics.requiredEvents
                );
            } finally {
                analytics.cleanup();
            }
        });
    }
});
