// tests/api/run-all.ts

import { exec } from 'child_process';
import { promisify } from 'util';
import { log } from './utils';

import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const execAsync = promisify(exec);

const testFiles = [
  '01-generation-basic.ts',
  '02-basic.ts',
  '03-flows.ts',
  '04-aliases.ts',
  '05-live.ts',
  '06-edge-cases.ts',
  '07-known-issues.ts',
  '08-auto-enhance.ts',
];

async function runTest(file: string): Promise<{ success: boolean; duration: number }> {
  const startTime = Date.now();

  try {
    log.section(`Running ${file}`);

    await execAsync(`tsx ${file}`, {
      cwd: __dirname,
      env: process.env,
    });

    const duration = Date.now() - startTime;
    log.success(`${file} completed (${duration}ms)`);

    return { success: true, duration };
  } catch (error) {
    const duration = Date.now() - startTime;
    log.error(`${file} failed (${duration}ms)`);
    console.error(error);

    return { success: false, duration };
  }
}

async function main() {
  console.log('\n');
  log.section('🚀 BANATIE API TEST SUITE');
  console.log('\n');

  const results: Array<{ file: string; success: boolean; duration: number }> = [];
  const startTime = Date.now();

  for (const file of testFiles) {
    const result = await runTest(file);
    results.push({ file, ...result });
    console.log('\n');
  }

  const totalDuration = Date.now() - startTime;

  // Summary
  log.section('📊 TEST SUMMARY');
  console.log('\n');

  const passed = results.filter(r => r.success).length;
  const failed = results.filter(r => !r.success).length;

  results.forEach(result => {
    const icon = result.success ? '✓' : '✗';
    const color = result.success ? '\x1b[32m' : '\x1b[31m';
    console.log(`${color}${icon}\x1b[0m ${result.file} (${result.duration}ms)`);
  });

  console.log('\n');
  log.info(`Total: ${results.length} test suites`);
  log.success(`Passed: ${passed}`);

  if (failed > 0) {
    log.error(`Failed: ${failed}`);
  }

  log.info(`Duration: ${(totalDuration / 1000).toFixed(2)}s`);
  console.log('\n');

  if (failed > 0) {
    process.exit(1);
  }
}

main().catch(error => {
  console.error('Test runner failed:', error);
  process.exit(1);
});
