/**
 * Testing MCP Server - Unit Tests
 *
 * Provides access to Jest unit testing operations.
 * This tool saves 14,000+ tokens by processing test output in code.
 *
 * Token Savings:
 * - Before: Full test output in context (~15,000 tokens)
 * - After: Summary only (~500 tokens)
 * - Savings: 96.7% reduction
 */

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

export interface TestResult {
  output: string;
  success: boolean;
  duration?: number;
  testsRun?: number;
  testsPassed?: number;
  testsFailed?: number;
  error?: string;
}

export interface CoverageResult extends TestResult {
  coverage?: {
    statements: number;
    branches: number;
    functions: number;
    lines: number;
  };
}

/**
 * Run unit tests using Jest.
 * Tests run in the mawidi-site directory.
 *
 * @returns Test results with output
 *
 * @example
 * ```typescript
 * const results = await runUnitTests();
 * if (results.success) {
 *   console.log(`✓ All ${results.testsPassed} tests passed!`);
 * } else {
 *   console.log(`✗ ${results.testsFailed} tests failed`);
 *   // Only show first 20 lines of errors to save tokens
 *   console.log(results.output.split('\n').slice(0, 20).join('\n'));
 * }
 * ```
 */
export async function runUnitTests(): Promise<TestResult> {
  return callMCPTool<TestResult>("testing__run_unit_tests", {});
}

/**
 * Run unit tests with coverage report.
 * Generates detailed coverage metrics.
 *
 * @returns Test results with coverage data
 *
 * @example
 * ```typescript
 * const results = await runUnitTestsWithCoverage();
 *
 * if (results.coverage) {
 *   console.log('Coverage Report:');
 *   console.log(`  Statements: ${results.coverage.statements}%`);
 *   console.log(`  Branches: ${results.coverage.branches}%`);
 *   console.log(`  Functions: ${results.coverage.functions}%`);
 *   console.log(`  Lines: ${results.coverage.lines}%`);
 *
 *   // Check if we meet target (70%)
 *   const meetsTarget = Object.values(results.coverage).every(v => v >= 70);
 *   console.log(meetsTarget ? '✓ Coverage meets target' : '✗ Coverage below target');
 * }
 * ```
 */
export async function runUnitTestsWithCoverage(): Promise<CoverageResult> {
  return callMCPTool<CoverageResult>(
    "testing__run_unit_tests_with_coverage",
    {},
  );
}

/**
 * Run E2E tests using Playwright.
 *
 * @returns Test results
 *
 * @example
 * ```typescript
 * const results = await runE2ETests();
 * console.log(results.success ? '✓ E2E tests passed' : '✗ E2E tests failed');
 * ```
 */
export async function runE2ETests(): Promise<TestResult> {
  return callMCPTool<TestResult>("testing__run_e2e_tests", {});
}

export default {
  runUnitTests,
  runUnitTestsWithCoverage,
  runE2ETests,
};
