/**
 * Testing MCP Server - E2E (Playwright)
 *
 * Provides Playwright end-to-end testing operations.
 * Token savings: 20,000+ per operation (very verbose output)
 */

import { callMCPTool } from "../../client.js";

export interface E2ETestResult {
  success: boolean;
  output: string;
  testsRun: number;
  testsPassed: number;
  testsFailed: number;
  duration: number;
  failures?: Array<{
    test: string;
    error: string;
  }>;
}

export interface RunE2EInput {
  headed?: boolean;
  browser?: "chromium" | "firefox" | "webkit";
  grep?: string;
  workers?: number;
}

/**
 * Run Playwright E2E tests.
 *
 * @param input - Test options
 * @returns Test results
 *
 * @example
 * ```typescript
 * // Run all E2E tests headless
 * const results = await runE2ETests();
 *
 * console.log(`Tests: ${results.testsPassed}/${results.testsRun} passed`);
 * console.log(`Duration: ${results.duration}ms`);
 *
 * if (!results.success && results.failures) {
 *   console.log('Failures:');
 *   results.failures.forEach(f => {
 *     console.log(`  - ${f.test}`);
 *     console.log(`    ${f.error.split('\n')[0]}`); // First line only
 *   });
 * }
 * ```
 */
export async function runE2ETests(
  input: RunE2EInput = {},
): Promise<E2ETestResult> {
  return callMCPTool<E2ETestResult>("testing__run_e2e_tests", input);
}

/**
 * Run E2E tests in headed mode (with browser UI).
 *
 * @param browser - Browser to use
 * @returns Test results
 *
 * @example
 * ```typescript
 * const results = await runE2EHeaded('chromium');
 * console.log('Ran tests in visible browser');
 * ```
 */
export async function runE2EHeaded(
  browser: "chromium" | "firefox" | "webkit" = "chromium",
): Promise<E2ETestResult> {
  return callMCPTool<E2ETestResult>("testing__run_e2e_tests", {
    headed: true,
    browser,
  });
}

/**
 * Run specific E2E test by name.
 *
 * @param testName - Test name or pattern
 * @returns Test results
 *
 * @example
 * ```typescript
 * const results = await runSpecificE2ETest('signup');
 * console.log(`Signup test: ${results.success ? '✓' : '✗'}`);
 * ```
 */
export async function runSpecificE2ETest(
  testName: string,
): Promise<E2ETestResult> {
  return callMCPTool<E2ETestResult>("testing__run_e2e_tests", {
    grep: testName,
  });
}

/**
 * Run E2E tests and generate report.
 *
 * @returns Test results with HTML report path
 *
 * @example
 * ```typescript
 * const results = await runE2EWithReport();
 * console.log(`Report: ${results.reportPath}`);
 * ```
 */
export async function runE2EWithReport(): Promise<
  E2ETestResult & { reportPath: string }
> {
  return callMCPTool("testing__run_e2e_with_report", {});
}

export default {
  runE2ETests,
  runE2EHeaded,
  runSpecificE2ETest,
  runE2EWithReport,
};
