import { test, expect } from '../fixtures';

/**
 * Scenario Management Tests
 * Covers: CRUD operations, status changes, pagination, filtering, bulk operations
 * Target: 100% coverage on critical paths
 */

test.describe('Scenario Management @scenarios @critical', () => {
  
  test('should create a new scenario', async ({ authenticatedPage }) => {
    await authenticatedPage.goto('/scenarios/new');
    
    // Fill scenario form
    await authenticatedPage.fill('[data-testid="scenario-name-input"]', 'E2E Test Scenario');
    await authenticatedPage.fill('[data-testid="scenario-description-input"]', 'Created during E2E testing');
    await authenticatedPage.selectOption('[data-testid="scenario-region-select"]', 'us-east-1');
    await authenticatedPage.fill('[data-testid="scenario-tags-input"]', 'e2e, test, automation');
    
    // Submit
    await authenticatedPage.click('[data-testid="create-scenario-button"]');
    
    // Assert redirect to detail page
    await authenticatedPage.waitForURL(/\/scenarios\/[\w-]+/);
    await expect(authenticatedPage.locator('[data-testid="scenario-detail-header"]')).toContainText('E2E Test Scenario');
    await expect(authenticatedPage.locator('[data-testid="scenario-status"]')).toContainText('draft');
  });

  test('should validate scenario creation form', async ({ authenticatedPage }) => {
    await authenticatedPage.goto('/scenarios/new');
    await authenticatedPage.click('[data-testid="create-scenario-button"]');
    
    // Assert validation errors
    await expect(authenticatedPage.locator('[data-testid="name-error"]')).toBeVisible();
    await expect(authenticatedPage.locator('[data-testid="region-error"]')).toBeVisible();
  });

  test('should edit existing scenario', async ({ authenticatedPage, testData }) => {
    // Create a scenario first
    const scenario = await testData.createScenario({
      name: 'Original Name',
      description: 'Original description',
      region: 'us-east-1',
      tags: ['original'],
    });
    
    // Navigate to edit
    await authenticatedPage.goto(`/scenarios/${scenario.id}/edit`);
    
    // Edit fields
    await authenticatedPage.fill('[data-testid="scenario-name-input"]', 'Updated Name');
    await authenticatedPage.fill('[data-testid="scenario-description-input"]', 'Updated description');
    await authenticatedPage.selectOption('[data-testid="scenario-region-select"]', 'eu-west-1');
    
    // Save
    await authenticatedPage.click('[data-testid="save-scenario-button"]');
    
    // Assert
    await authenticatedPage.waitForURL(`/scenarios/${scenario.id}`);
    await expect(authenticatedPage.locator('[data-testid="scenario-name"]')).toContainText('Updated Name');
    await expect(authenticatedPage.locator('[data-testid="scenario-region"]')).toContainText('eu-west-1');
  });

  test('should delete scenario', async ({ authenticatedPage, testData }) => {
    const scenario = await testData.createScenario({
      name: 'To Be Deleted',
      region: 'us-east-1',
      tags: [],
    });
    
    await authenticatedPage.goto(`/scenarios/${scenario.id}`);
    await authenticatedPage.click('[data-testid="delete-scenario-button"]');
    await authenticatedPage.click('[data-testid="confirm-delete-button"]');
    
    // Assert redirect to list
    await authenticatedPage.waitForURL('/scenarios');
    await expect(authenticatedPage.locator('[data-testid="delete-success-toast"]')).toBeVisible();
    await expect(authenticatedPage.locator(`text=${scenario.name}`)).not.toBeVisible();
  });

  test('should start and stop scenario', async ({ authenticatedPage, testData }) => {
    const scenario = await testData.createScenario({
      name: 'Start Stop Test',
      region: 'us-east-1',
      tags: [],
    });
    
    await authenticatedPage.goto(`/scenarios/${scenario.id}`);
    
    // Start scenario
    await authenticatedPage.click('[data-testid="start-scenario-button"]');
    await expect(authenticatedPage.locator('[data-testid="scenario-status"]')).toContainText('running');
    
    // Stop scenario
    await authenticatedPage.click('[data-testid="stop-scenario-button"]');
    await authenticatedPage.click('[data-testid="confirm-stop-button"]');
    await expect(authenticatedPage.locator('[data-testid="scenario-status"]')).toContainText('completed');
  });

  test('should archive and unarchive scenario', async ({ authenticatedPage, testData }) => {
    const scenario = await testData.createScenario({
      name: 'Archive Test',
      region: 'us-east-1',
      tags: [],
      status: 'completed',
    });
    
    await authenticatedPage.goto(`/scenarios/${scenario.id}`);
    
    // Archive
    await authenticatedPage.click('[data-testid="archive-scenario-button"]');
    await authenticatedPage.click('[data-testid="confirm-archive-button"]');
    await expect(authenticatedPage.locator('[data-testid="scenario-status"]')).toContainText('archived');
    
    // Unarchive
    await authenticatedPage.click('[data-testid="unarchive-scenario-button"]');
    await expect(authenticatedPage.locator('[data-testid="scenario-status"]')).toContainText('completed');
  });
});

test.describe('Scenario List @scenarios', () => {
  
  test('should display scenarios list with pagination', async ({ authenticatedPage }) => {
    await authenticatedPage.goto('/scenarios');
    
    // Check list is visible
    await expect(authenticatedPage.locator('[data-testid="scenarios-list"]')).toBeVisible();
    await expect(authenticatedPage.locator('[data-testid="scenario-item"]')).toHaveCount.greaterThan(0);
    
    // Test pagination if multiple pages
    const nextButton = authenticatedPage.locator('[data-testid="pagination-next"]');
    if (await nextButton.isVisible().catch(() => false)) {
      await nextButton.click();
      await expect(authenticatedPage.locator('[data-testid="page-number"]')).toContainText('2');
    }
  });

  test('should filter scenarios by status', async ({ authenticatedPage }) => {
    await authenticatedPage.goto('/scenarios');
    
    // Filter by running
    await authenticatedPage.selectOption('[data-testid="status-filter"]', 'running');
    await authenticatedPage.waitForTimeout(500); // Wait for filter to apply
    
    // Verify only running scenarios are shown
    const statusBadges = await authenticatedPage.locator('[data-testid="scenario-status-badge"]').all();
    for (const badge of statusBadges) {
      await expect(badge).toContainText('running');
    }
  });

  test('should filter scenarios by region', async ({ authenticatedPage }) => {
    await authenticatedPage.goto('/scenarios');
    
    await authenticatedPage.selectOption('[data-testid="region-filter"]', 'us-east-1');
    await authenticatedPage.waitForTimeout(500);
    
    // Verify regions match
    const regions = await authenticatedPage.locator('[data-testid="scenario-region"]').all();
    for (const region of regions) {
      await expect(region).toContainText('us-east-1');
    }
  });

  test('should search scenarios by name', async ({ authenticatedPage }) => {
    await authenticatedPage.goto('/scenarios');
    
    await authenticatedPage.fill('[data-testid="search-input"]', 'Test');
    await authenticatedPage.press('[data-testid="search-input"]', 'Enter');
    
    // Verify search results
    await expect(authenticatedPage.locator('[data-testid="scenarios-list"]')).toBeVisible();
  });

  test('should sort scenarios by different criteria', async ({ authenticatedPage }) => {
    await authenticatedPage.goto('/scenarios');
    
    // Sort by name
    await authenticatedPage.click('[data-testid="sort-by-name"]');
    await expect(authenticatedPage.locator('[data-testid="sort-indicator-name"]')).toBeVisible();
    
    // Sort by date
    await authenticatedPage.click('[data-testid="sort-by-date"]');
    await expect(authenticatedPage.locator('[data-testid="sort-indicator-date"]')).toBeVisible();
  });
});

test.describe('Bulk Operations @scenarios @bulk', () => {
  
  test('should select multiple scenarios', async ({ authenticatedPage, testData }) => {
    // Create multiple scenarios
    await Promise.all([
      testData.createScenario({ name: 'Bulk 1', region: 'us-east-1', tags: [] }),
      testData.createScenario({ name: 'Bulk 2', region: 'us-east-1', tags: [] }),
      testData.createScenario({ name: 'Bulk 3', region: 'us-east-1', tags: [] }),
    ]);
    
    await authenticatedPage.goto('/scenarios');
    
    // Select multiple
    await authenticatedPage.click('[data-testid="select-all-checkbox"]');
    
    // Verify selection
    await expect(authenticatedPage.locator('[data-testid="bulk-actions-bar"]')).toBeVisible();
    await expect(authenticatedPage.locator('[data-testid="selected-count"]')).toContainText('3');
  });

  test('should bulk delete scenarios', async ({ authenticatedPage, testData }) => {
    // Create scenarios
    const scenarios = await Promise.all([
      testData.createScenario({ name: 'Delete 1', region: 'us-east-1', tags: [] }),
      testData.createScenario({ name: 'Delete 2', region: 'us-east-1', tags: [] }),
    ]);
    
    await authenticatedPage.goto('/scenarios');
    
    // Select and delete
    await authenticatedPage.click('[data-testid="select-all-checkbox"]');
    await authenticatedPage.click('[data-testid="bulk-delete-button"]');
    await authenticatedPage.click('[data-testid="confirm-bulk-delete-button"]');
    
    await expect(authenticatedPage.locator('[data-testid="bulk-delete-success"]')).toBeVisible();
  });

  test('should bulk export scenarios', async ({ authenticatedPage, testData }) => {
    const scenarios = await Promise.all([
      testData.createScenario({ name: 'Export 1', region: 'us-east-1', tags: [] }),
      testData.createScenario({ name: 'Export 2', region: 'us-east-1', tags: [] }),
    ]);
    
    await authenticatedPage.goto('/scenarios');
    
    // Select and export
    await authenticatedPage.click('[data-testid="select-all-checkbox"]');
    await authenticatedPage.click('[data-testid="bulk-export-button"]');
    
    // Wait for download
    const [download] = await Promise.all([
      authenticatedPage.waitForEvent('download'),
      authenticatedPage.click('[data-testid="export-json-button"]'),
    ]);
    
    expect(download.suggestedFilename()).toContain('.json');
  });
});

test.describe('Scenario Detail View @scenarios', () => {
  
  test('should display scenario metrics', async ({ authenticatedPage, testData }) => {
    const scenario = await testData.createScenario({
      name: 'Metrics Test',
      region: 'us-east-1',
      tags: [],
    });
    
    // Add some test data
    await testData.addScenarioLogs(scenario.id, 10);
    
    await authenticatedPage.goto(`/scenarios/${scenario.id}`);
    
    // Check metrics are displayed
    await expect(authenticatedPage.locator('[data-testid="metrics-card"]')).toBeVisible();
    await expect(authenticatedPage.locator('[data-testid="total-requests"]')).toBeVisible();
    await expect(authenticatedPage.locator('[data-testid="estimated-cost"]')).toBeVisible();
  });

  test('should display cost breakdown chart', async ({ authenticatedPage, testData }) => {
    const scenario = await testData.createScenario({
      name: 'Chart Test',
      region: 'us-east-1',
      tags: [],
    });
    
    await authenticatedPage.goto(`/scenarios/${scenario.id}`);
    
    // Check chart is visible
    await expect(authenticatedPage.locator('[data-testid="cost-breakdown-chart"]')).toBeVisible();
  });

  test('should display logs tab', async ({ authenticatedPage, testData }) => {
    const scenario = await testData.createScenario({
      name: 'Logs Test',
      region: 'us-east-1',
      tags: [],
    });
    
    await authenticatedPage.goto(`/scenarios/${scenario.id}`);
    await authenticatedPage.click('[data-testid="logs-tab"]');
    
    await expect(authenticatedPage.locator('[data-testid="logs-table"]')).toBeVisible();
  });

  test('should display PII detection results', async ({ authenticatedPage, testData }) => {
    const scenario = await testData.createScenario({
      name: 'PII Test',
      region: 'us-east-1',
      tags: [],
    });
    
    // Add log with PII
    await testData.addScenarioLogWithPII(scenario.id);
    
    await authenticatedPage.goto(`/scenarios/${scenario.id}`);
    await authenticatedPage.click('[data-testid="pii-tab"]');
    
    await expect(authenticatedPage.locator('[data-testid="pii-alerts"]')).toBeVisible();
  });
});
