/**
 * Global Teardown for FoundryVTT E2E Tests
 * 
 * Nettoie après l'exécution des tests :
 * - Supprime le monde de test
 * - Nettoie les fichiers temporaires
 */

import { chromium } from '@playwright/test';

const FOUNDRY_BASE_URL = 'http://localhost:30000';
const TEST_WORLD_NAME = process.env.FOUNDRY_TEST_WORLD || 'VVM-E2E-Test-World';

/**
 * Supprime le monde de test
 */
async function deleteTestWorld(page) {
  console.log('🗑️  Deleting test world...');
  
  try {
    await page.goto(`${FOUNDRY_BASE_URL}/setup`, { timeout: 30000 });
    await page.waitForSelector('#world-list', { timeout: 30000 });
    
    // Trouver le monde de test
    const worldRow = page.locator(`#world-list [data-world-id]:has-text("${TEST_WORLD_NAME}")`);
    
    if (await worldRow.count() > 0) {
      // Ouvrir le menu du monde
      await worldRow.locator('.world-actions-button').click();
      await page.waitForSelector('.world-context-menu', { timeout: 5000 });
      
      // Cliquer sur Supprimer
      await page.locator('.world-context-menu [data-action="delete"]').click();
      
      // Confirmer la suppression
      await page.waitForSelector('.delete-confirmation-dialog', { timeout: 5000 });
      await page.locator('.delete-confirmation-dialog button:has-text("Delete")').click();
      
      // Attendre la suppression
      await page.waitForSelector(`#world-list [data-world-id]:has-text("${TEST_WORLD_NAME}")`, {
        state: 'detached',
        timeout: 10000
      });
      
      console.log(`✅ Deleted test world: ${TEST_WORLD_NAME}`);
    } else {
      console.log(`⚠️  Test world "${TEST_WORLD_NAME}" not found, skipping deletion`);
    }
  } catch (error) {
    console.log('⚠️  Could not delete test world (may have already been deleted):', error.message);
  }
}

/**
 * Nettoie les utilisateurs de test
 */
async function cleanupTestUsers(page) {
  console.log('🧹 Cleaning up test users...');
  
  try {
    const testUsers = [
      process.env.FOUNDRY_TEST_GM || 'TestGM',
      process.env.FOUNDRY_TEST_PLAYER || 'TestPlayer'
    ];
    
    await page.goto(`${FOUNDRY_BASE_URL}/setup/users`, { timeout: 30000 });
    await page.waitForSelector('#users-list', { timeout: 30000 });
    
    for (const username of testUsers) {
      const userRow = page.locator(`#users-list [data-user-id]:has-text("${username}")`);
      
      if (await userRow.count() > 0) {
        await userRow.locator('.user-actions-button').click();
        await page.waitForSelector('.user-context-menu', { timeout: 5000 });
        await page.locator('.user-context-menu [data-action="delete"]').click();
        await page.locator('.delete-confirmation-dialog button:has-text("Delete")').click();
        
        await page.waitForSelector(`#users-list [data-user-id]:has-text("${username}")`, {
          state: 'detached',
          timeout: 5000
        });
        
        console.log(`✅ Deleted test user: ${username}`);
      }
    }
  } catch (error) {
    console.log('⚠️  Could not cleanup test users:', error.message);
  }
}

/**
 * Exécute le nettoyage
 */
async function globalTeardown() {
  console.log('\n🧹 Running FoundryVTT E2E Test Teardown...\n');
  
  const browser = await chromium.launch({
    headless: true,
    timeout: 30000,
  });
  
  const context = await browser.newContext({
    viewport: { width: 1920, height: 1080 },
    userAgent: 'VVM-E2E-Teardown/1.0',
  });
  
  const page = await context.newPage();
  
  try {
    await page.goto(FOUNDRY_BASE_URL, { timeout: 30000 });
    
    // Supprimer le monde de test
    await deleteTestWorld(page);
    
    // Nettoyer les utilisateurs
    await cleanupTestUsers(page);
    
    console.log('\n✅ FoundryVTT E2E Test Teardown Complete!\n');
    
  } catch (error) {
    console.error('❌ Teardown failed:', error);
  } finally {
    await page.close();
    await context.close();
    await browser.close();
  }
}

export default globalTeardown;
