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

/** File purpose (plain language): supplies the same developer login fixture to every asset browser test without changing production authentication code. */
export const test = base;

/** Plain purpose: register deterministic authentication responses before a test opens a protected route. Related files: auth-store.js, router/index.js, and all files in frontend/tests. Data flow: test setup -> mocked current-user/CSRF requests -> route guard -> protected page. */
test.beforeEach(async ({ page }) => {
  /** Plain purpose: add the browser-visible CSRF Cookie used by the shared request helper in either local Playwright port. Related files: auth-api-client.js, SecurityConfig.java. Flow: test context Cookie -> X-XSRF-TOKEN header -> protected request fixture. */
  await page.context().addCookies([{ name: 'XSRF-TOKEN', value: 'playwright-csrf', domain: '127.0.0.1', path: '/' }]);
  const user = {
    id: 1,
    username: 'playwright-asset-admin',
    roleCode: 'DEVELOPER',
    pagePermissions: {
      overview: 'EDIT',
      domain: 'EDIT',
      'reference-wecom': 'EDIT',
      'phone-assets': 'EDIT',
      alerts: 'EDIT'
    }
  };

  /** Plain purpose: return an administrator identity to the route guard. Related files: auth-store.js and router/index.js. Data flow: GET /api/auth/me -> mocked envelope -> auth state -> allowed route. */
  await page.route('**/api/auth/me', async route => route.fulfill({
    contentType: 'application/json',
    body: JSON.stringify({ code: 200, message: 'success', data: user })
  }));

  /** Plain purpose: make protected test requests receive a successful CSRF preflight. Related files: api-client.js and all asset API clients. Data flow: API client -> CSRF request -> mocked success -> test-owned business request mock. */
  await page.route('**/api/auth/csrf', async route => route.fulfill({
    contentType: 'application/json',
    body: JSON.stringify({ code: 200, message: 'success', data: null })
  }));
});

export { expect };
