/* eslint-disable */
import {devices, defineConfig} from '@playwright/test';
import * as dotenv from 'dotenv';

dotenv.config();

if (!process.env.CAMUNDA_OPTIMIZE_BASE_URL && process.env.BASE_URL) {
  process.env.CAMUNDA_OPTIMIZE_BASE_URL = `https://${process.env.BASE_URL}/optimize`;
}

const projectName = process.env.PROJECT! || 'Chromium'; // Default to 'default-project' if PROJECT is not set

const testRailOptions = {
  embedAnnotationsAsProperties: true,
  outputFile: './test-results/junit-report.xml',
};

// Define reporters without SlackReporter
const useReportersWithoutSlack: any[] = [
  ['list'],
  ['junit', testRailOptions],
  ['html', {outputFolder: 'html-report'}],
  ['json', {outputFile: `json-report/results.json`}],
];

// Define reporters with SlackReporter
const useReportersWithSlack: any[] = [
  [
    './node_modules/playwright-slack-report/dist/src/SlackReporter.js',
    {
      slackOAuthToken: process.env.SLACK_BOT_USER_OAUTH_TOKEN!,
      channels: ['c8-cross-component-test-results'],
      sendResults: 'always',
      showInThread: true,
      meta: [
        {
          key: (() => {
            switch (process.env.MINOR_VERSION) {
              case 'c8Run-8.10': {
                const tasklistSuffix = process.env.TASKLIST_VERSION
                  ? ` - Tasklist ${process.env.TASKLIST_VERSION.toUpperCase()} mode`
                  : '';
                const dockerSuffix =
                  process.env.RUN_AS_DOCKER_COMPOSE === 'true'
                    ? ' - Docker Compose'
                    : '';
                const databaseSuffix = process.env.DATABASE
                  ? ` - Database ${process.env.DATABASE.toUpperCase()}`
                  : '';
                return `Test Results for c8Run with 8.10-SNAPSHOT version - OS: ${process.env.OS}${tasklistSuffix}${dockerSuffix}${databaseSuffix}`;
              }
              case 'c8Run-8.9': {
                const tasklistSuffix = process.env.TASKLIST_VERSION
                  ? ` - Tasklist ${process.env.TASKLIST_VERSION.toUpperCase()} mode`
                  : '';
                const dockerSuffix =
                  process.env.RUN_AS_DOCKER_COMPOSE === 'true'
                    ? ' - Docker Compose'
                    : '';
                const databaseSuffix = process.env.DATABASE
                  ? ` - Database ${process.env.DATABASE.toUpperCase()}`
                  : '';
                return `Test Results for c8Run with 8.9-SNAPSHOT version - OS: ${process.env.OS}${tasklistSuffix}${dockerSuffix}${databaseSuffix}`;
              }
              case 'c8Run-8.8': {
                const tasklistSuffix = process.env.TASKLIST_VERSION
                  ? ` - Tasklist ${process.env.TASKLIST_VERSION.toUpperCase()} mode`
                  : '';
                const dockerSuffix =
                  process.env.RUN_AS_DOCKER_COMPOSE === 'true'
                    ? ' - Docker Compose'
                    : '';
                const databaseSuffix = process.env.DATABASE
                  ? ` - Database ${process.env.DATABASE.toUpperCase()}`
                  : '';
                return `Test Results for c8Run with 8.8-SNAPSHOT version - OS: ${process.env.OS}${tasklistSuffix}${dockerSuffix}${databaseSuffix}`;
              }
              case 'c8Run-8.7': {
                const dockerSuffix =
                  process.env.RUN_AS_DOCKER_COMPOSE === 'true'
                    ? ' - Docker Compose'
                    : '';
                const databaseSuffix = process.env.DATABASE
                  ? ` - Database ${process.env.DATABASE.toUpperCase()}`
                  : '';
                return `Test Results for c8Run with 8.7-SNAPSHOT version - OS: ${process.env.OS}${dockerSuffix}${databaseSuffix}`;
              }
              case 'SM-8.10': {
                const searchEngine =
                  process.env.SEARCH_ENGINE || 'Elasticsearch';
                const isRBA = process.env.IS_RBA === 'true';
                const isMT = process.env.IS_MT === 'true';
                const isDS = process.env.IS_DS === 'true';
                const isLICENSEKEY = process.env.IS_LICENSE_KEY === 'true';

                let suffix = '';
                if (isRBA) suffix += ' - RBA';
                if (isMT) suffix += ' - Multi-Tenancy';
                if (isDS) suffix += ' - DocumentStore';
                if (isLICENSEKEY)
                  suffix += ` - License-Key- ${process.env.LICENSE_KEY}`;
                const tasklistSuffix = process.env.TASKLIST_VERSION
                  ? ` - Tasklist ${process.env.TASKLIST_VERSION.toUpperCase()} mode`
                  : '';
                suffix += tasklistSuffix;

                return `Test Results for Self-Managed with Helm with Latest 8.10-SNAPSHOT Versions (${searchEngine})${suffix} - ${projectName}`;
              }
              case 'SM-8.9': {
                const searchEngine =
                  process.env.SEARCH_ENGINE || 'Elasticsearch';
                const isRBA = process.env.IS_RBA === 'true';
                const isMT = process.env.IS_MT === 'true';
                const isDS = process.env.IS_DS === 'true';
                const isLICENSEKEY = process.env.IS_LICENSE_KEY === 'true';

                let suffix = '';
                if (isRBA) suffix += ' - RBA';
                if (isMT) suffix += ' - Multi-Tenancy';
                if (isDS) suffix += ' - DocumentStore';
                if (isLICENSEKEY)
                  suffix += ` - License-Key- ${process.env.LICENSE_KEY}`;
                const tasklistSuffix = process.env.TASKLIST_VERSION
                  ? ` - Tasklist ${process.env.TASKLIST_VERSION.toUpperCase()} mode`
                  : '';
                suffix += tasklistSuffix;

                return `Test Results for Self-Managed with Helm with Latest 8.9-SNAPSHOT Versions (${searchEngine})${suffix} - ${projectName}`;
              }
              case 'SM-8.8': {
                const searchEngine =
                  process.env.SEARCH_ENGINE || 'Elasticsearch';
                const isRBA = process.env.IS_RBA === 'true';
                const isMT = process.env.IS_MT === 'true';
                const isDS = process.env.IS_DS === 'true';
                const isMigration = process.env.IS_MIGRATION === 'true';
                const isLICENSEKEY = process.env.IS_LICENSE_KEY === 'true';

                let suffix = '';
                if (isRBA) suffix += ' - RBA';
                if (isMT) suffix += ' - Multi-Tenancy';
                if (isMigration) suffix += ' - Migration Path';
                if (isDS) suffix += ' - DocumentStore';
                if (isLICENSEKEY)
                  suffix += ` - License-Key- ${process.env.LICENSE_KEY}`;
                const tasklistSuffix = process.env.TASKLIST_VERSION
                  ? ` - Tasklist ${process.env.TASKLIST_VERSION.toUpperCase()} mode`
                  : '';
                suffix += tasklistSuffix;

                return `Test Results for Self-Managed with Helm with Latest 8.8-SNAPSHOT Versions (${searchEngine})${suffix} - ${projectName}`;
              }
              case 'SM-8.7': {
                const searchEngine =
                  process.env.SEARCH_ENGINE || 'Elasticsearch';
                const isRBA = process.env.IS_RBA === 'true';
                const isMT = process.env.IS_MT === 'true';
                const isLICENSEKEY = process.env.IS_LICENSE_KEY === 'true';

                let suffix = '';
                if (isRBA) suffix += ' - RBA';
                if (isMT) suffix += ' - Multi-Tenancy';
                if (isLICENSEKEY)
                  suffix += ` - License-Key- ${process.env.LICENSE_KEY}`;

                return `Test Results for Self-Managed with Helm with Latest 8.7-SNAPSHOT Versions (${searchEngine})${suffix} - ${projectName}`;
              }
              case '8.7':
                return process.env.RELEASE_VERSION === 'true'
                  ? 'Test Results for SaaS with a Cluster with latest 8.7 versions of all components'
                  : 'Test Results for SaaS with a Cluster with 8.7-SNAPSHOT versions of all components';
              case '8.8': {
                const baseMessage =
                  process.env.RELEASE_VERSION === 'true'
                    ? 'Test Results for SaaS with a Cluster with latest 8.8 versions of all components'
                    : 'Test Results for SaaS with a Cluster with 8.8-SNAPSHOT versions of all components';
                const tasklistSuffix = process.env.TASKLIST_VERSION
                  ? ` - Tasklist ${process.env.TASKLIST_VERSION.toUpperCase()} mode`
                  : '';
                return `${baseMessage}${tasklistSuffix}`;
              }
              case '8.9': {
                const baseMessage =
                  process.env.RELEASE_VERSION === 'true'
                    ? 'Test Results for SaaS with a Cluster with latest 8.9 versions of all components'
                    : 'Test Results for SaaS with a Cluster with 8.9-SNAPSHOT versions of all components';
                const tasklistSuffix = process.env.TASKLIST_VERSION
                  ? ` - Tasklist ${process.env.TASKLIST_VERSION.toUpperCase()} mode`
                  : '';
                return `${baseMessage}${tasklistSuffix}`;
              }
              case '8.10': {
                const baseMessage =
                  process.env.RELEASE_VERSION === 'true'
                    ? 'Test Results for SaaS with a Cluster with latest 8.10 versions of all components'
                    : 'Test Results for SaaS with a Cluster with 8.10-SNAPSHOT versions of all components';
                const tasklistSuffix = process.env.TASKLIST_VERSION
                  ? ` - Tasklist ${process.env.TASKLIST_VERSION.toUpperCase()} mode`
                  : '';
                return `${baseMessage}${tasklistSuffix}`;
              }
              default:
                return 'Test Results';
            }
          })(),
          value: `<https://github.com/camunda/c8-cross-component-e2e-tests/actions/runs/${process.env.GITHUB_RUN_ID}|📊>`,
        },
      ],
    },
  ],
  ...useReportersWithoutSlack,
];

const args = process.argv.slice(2);
const changedFoldersArgIndex = args.indexOf('--changed-folders');
const changedFolders =
  changedFoldersArgIndex !== -1
    ? args[changedFoldersArgIndex + 1].split(',')
    : [];

const timeout = () => {
  if (process.env.MINOR_VERSION?.includes('SM-8.7')) {
    // OpenSearch indexes more slowly than Elasticsearch — give SM-8.7 the
    // full 12 minute budget so non-`test.slow()` flows don't hit 3-min cap.
    if (String(process.env.IS_OPENSEARCH).toLowerCase() === 'true') {
      return 12 * 60 * 1000;
    }
    return 3 * 60 * 1000;
  }
  return 12 * 60 * 1000;
};

const workerCount = () => {
  if (process.env.MINOR_VERSION?.includes('SM-8.7')) {
    return process.env.CI === 'true' ? 37 : '100%';
  }
  if (process.env.MINOR_VERSION?.includes('SM')) {
    return 25;
  }

  return 37;
};

const dependencies = (project: string) => {
  if (process.env.MINOR_VERSION?.includes('SM-8.7')) {
    return undefined;
  }
  return [`${project}-setup`];
};

export default defineConfig({
  testDir: process.env.MINOR_VERSION
    ? `./tests/${process.env.MINOR_VERSION}/`
    : `./tests/`,
  timeout: timeout(),
  workers: workerCount(),
  retries: 1,
  fullyParallel: false,
  use: {
    baseURL: getBaseURL(),
    actionTimeout: 10000,
    // Stage 5: trace on-first-retry. With retries=1, a passing-on-retry
    // test (i.e., a flake) leaves a trace from the first attempt — exactly
    // the cases worth debugging. Green runs pay no trace cost.
    trace: (process.env.C8E2E_TRACE as 'on' | 'off' | 'retain-on-failure' | 'on-first-retry') || 'on-first-retry',
    video: (process.env.C8E2E_VIDEO as 'on' | 'off' | 'retain-on-failure') || 'off',
  },
  projects: [
    {
      name: 'chromium',
      use: devices['Desktop Chrome'],
      dependencies: dependencies('chromium'),
      // Specify only tests in the changed folders for the 'chromium' project
      testMatch: changedFolders.includes('chromium')
        ? changedFolders.map((folder) => `**/${folder}/*.spec.ts`)
        : undefined,
      testIgnore: /test-setup\.spec\.[jt]s$/,
    },
    {
      name: 'firefox',
      use: devices['Desktop Firefox'],
      dependencies: dependencies('firefox'),
      testIgnore: /test-setup\.spec\.[jt]s$/,
    },
    {
      name: 'msedge',
      use: {
        ...devices['Desktop Edge'],
        browserName: 'chromium',
        channel: 'msedge',
      },
      dependencies: dependencies('msedge'),
      testIgnore: /test-setup\.spec\.[jt]s$/,
    },
    {
      name: 'chromium-setup',
      testMatch: /test-setup\.spec\.[jt]s$/,
      use: devices['Desktop Chrome'],
    },
    {
      name: 'firefox-setup',
      testMatch: /test-setup\.spec\.[jt]s$/,
      use: devices['Desktop Firefox'],
    },
    {
      name: 'msedge-setup',
      testMatch: /test-setup\.spec\.[jt]s$/,
      use: {
        ...devices['Desktop Edge'],
        browserName: 'chromium',
        channel: 'msedge',
      },
    },

    {
      name: 'chromium-v1',
      use: {
        ...devices['Desktop Chrome'],
        extraHTTPHeaders: {
          'X-Test-Tasklist-Version': 'v1',
        },
      },
      dependencies: ['chromium-v1-setup'],
      testIgnore: /test-setup\.spec\.[jt]s$/,
      grep: /^(?!.*@tasklistV2).*$/,
    },

    {
      name: 'chromium-v2',
      use: {
        ...devices['Desktop Chrome'],
        extraHTTPHeaders: {
          'X-Test-Tasklist-Version': 'v2',
        },
      },
      dependencies: ['chromium-v2-setup'],
      testIgnore: /test-setup\.spec\.[jt]s$/,
      grep: /^(?!.*@tasklistV1).*$/,
    },

    {
      name: 'chromium-v1-setup',
      testMatch: /test-setup\.spec\.[jt]s$/,
      use: {
        ...devices['Desktop Chrome'],
        extraHTTPHeaders: {
          'X-Test-Tasklist-Version': 'v1',
        },
      },
    },

    {
      name: 'chromium-v2-setup',
      testMatch: /test-setup\.spec\.[jt]s$/,
      use: {
        ...devices['Desktop Chrome'],
        extraHTTPHeaders: {
          'X-Test-Tasklist-Version': 'v2',
        },
      },
    },
  ],
  reporter:
    process.env.INCLUDE_SLACK_REPORTER === 'true'
      ? useReportersWithSlack
      : useReportersWithoutSlack,
});

function getBaseURL(): string {
  if (process.env.IS_PROD === 'true') {
    return 'https://console.camunda.io';
  }

  if (typeof process.env.PLAYWRIGHT_BASE_URL === 'string') {
    return process.env.PLAYWRIGHT_BASE_URL;
  }

  if (process.env.MINOR_VERSION?.includes('SM')) {
    return 'https://gke-' + process.env.BASE_URL + '.ci.distro.ultrawombat.com';
  }

  if (
    process.env.MINOR_VERSION?.includes('Run') &&
    process.env.MINOR_VERSION?.includes('8.8') &&
    process.env.RUN_AS_DOCKER_COMPOSE === 'true'
  ) {
    return 'http://localhost:8088';
  }

  if (process.env.MINOR_VERSION?.includes('Run')) {
    return 'http://localhost:8080';
  }

  return 'https://console.ultrawombat.com';
}
