/**
 * Authenticated test fixture.
 *
 * Extends Playwright's `test` with:
 *  - `storageState` pointing at the auth state saved by global-setup.ts
 *  - `seedData` exposing IDs written by E2ESeedCommand for URL construction
 *
 * Usage:
 *   import { test, expect } from '../fixtures/auth';
 *
 *   test('my journey', async ({ page, seedData }) => {
 *     await page.goto(`/sites/${seedData.siteId}/recommendations`);
 *   });
 */

import { test as base } from '@playwright/test';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export interface E2ESeedData {
  userId: number;
  siteId: number;
  siteName: string;
  analysisRunId: number;
  recommendationId: number;
  aiDraftId: number;
  wpPostId: number;
}

function loadSeedData(): E2ESeedData {
  const seedDataPath = path.join(__dirname, '..', '.seed-data.json');
  if (!fs.existsSync(seedDataPath)) {
    throw new Error(
      `E2E seed data not found at ${seedDataPath}. Did global setup run? Check that globalSetup is configured in playwright.config.ts.`,
    );
  }
  return JSON.parse(fs.readFileSync(seedDataPath, 'utf8')) as E2ESeedData;
}

export const test = base.extend<{
  seedData: E2ESeedData;
}>({
  // All tests using this fixture start with the E2E test user already logged in.
  storageState: path.join(__dirname, '..', '.auth-state.json'),

  // Provides the IDs seeded by E2ESeedCommand so tests can construct URLs.
  // eslint-disable-next-line no-empty-pattern
  seedData: async ({}, use) => {
    await use(loadSeedData());
  },
});

export { expect } from '@playwright/test';
