/**
 * Global Teardown for Playwright E2E Tests
 * 
 * This runs once after all test suites complete.
 * Used for:
 * - Database cleanup
 * - Test artifact archival
 * - Environment reset
 */

import { execSync } from 'child_process';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';

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

async function globalTeardown() {
  console.log('🧹 Starting E2E test teardown...');

  const testStartTime = process.env.TEST_START_TIME;
  console.log(`   Test started at: ${testStartTime}`);
  console.log(`   Test completed at: ${new Date().toISOString()}`);

  // Clean up temporary test files if in CI mode
  if (process.env.CI) {
    console.log('   CI mode: Cleaning up temporary files...');
    const resultsDir = path.join(__dirname, '..', 'e2e-results');
    
    // Keep videos/screenshots of failures for debugging
    // but clean up successful test artifacts after 7 days
    if (fs.existsSync(resultsDir)) {
      const files = fs.readdirSync(resultsDir);
      let cleanedCount = 0;
      
      for (const file of files) {
        const filePath = path.join(resultsDir, file);
        const stats = fs.statSync(filePath);
        const ageInDays = (Date.now() - stats.mtime.getTime()) / (1000 * 60 * 60 * 24);
        
        if (ageInDays > 7 && !file.includes('failed')) {
          try {
            fs.unlinkSync(filePath);
            cleanedCount++;
          } catch (e) {
            // Ignore errors during cleanup
          }
        }
      }
      
      console.log(`   Cleaned up ${cleanedCount} old test artifacts`);
    }
  }

  console.log('✅ E2E test teardown complete');
}

export default globalTeardown;
