/* eslint-disable react-hooks/rules-of-hooks */
import { test as base, Page, expect as baseExpect } from '@playwright/test';
import { mockAngularAPIs } from './angular-api-mock';

export type CrossAppFixtures = {
  locale: string;
  app: 'angular' | 'react';
  localePath: (path: string) => string;
  urlPattern: (path: string) => RegExp;
  page: Page;
};

export async function mockAllAPIs(page: Page): Promise<void> {
  await mockAngularAPIs(page);
}

export const test = base.extend<CrossAppFixtures>({
  locale: ['ru-ru', { option: true }],
  app: [
    // eslint-disable-next-line no-empty-pattern
    async ({}, use, testInfo) => {
      const projectName = testInfo.project.name;
      const app = projectName.startsWith('angular-') ? 'angular' : 'react';
      await use(app as 'angular' | 'react');
    },
    { auto: true },
  ],
  localePath: async ({ locale, app }, use) => {
    await use((path: string) => {
      const cleanPath = path.startsWith('/') ? path.slice(1) : path;
      if (app === 'angular') {
        return `/${cleanPath}`;
      }
      return `/${locale}/${cleanPath}`;
    });
  },
  urlPattern: async ({ locale, app }, use) => {
    await use((path: string) => {
      const cleanPath = path.replace(/^\//, '');
      if (app === 'angular') {
        return new RegExp(`/${cleanPath}`);
      }
      return new RegExp(`/${locale}/${cleanPath}`);
    });
  },
  page: async ({ page }, use) => {
    await mockAllAPIs(page);
    await use(page);
  },
});

export { baseExpect as expect };

export function urlContains(
  url: string,
  path: string,
  app: 'angular' | 'react',
  locale: string,
): boolean {
  const cleanPath = path.replace(/^\//, '');
  if (app === 'angular') {
    return url.includes(`/${cleanPath}`);
  }
  return url.includes(`/${locale}/${cleanPath}`);
}
