import { type Drupal } from '@drupal/playwright';
import { expect } from '@playwright/test';
import fs from 'fs';
import path from 'path';

export async function setupSite({ drupal }: { drupal: Drupal }) {
  const page = drupal.page;

  try {
    await drupal.setTestCookie();
    await drupal.loginAsAdmin();
    await drupal.installModules(['conductor']);
    await drupal.enableTestExtensions();
    await drupal.installModules(['conductor_test', 'http_request_mock']);

    await page.goto('/admin/config/system/keys/add');
    await page.fill('[data-drupal-selector="edit-label"]', 'conductor');
    const originalId = await page.locator('#edit-settings').getAttribute('id');
    await page.selectOption('[data-drupal-selector="edit-key-type"]', 'authentication_multivalue');
    await page.waitForFunction((oldId) => {
      const element = document.querySelector('[data-drupal-selector="edit-settings"]');
      return element && element.id !== oldId;
    }, originalId);
    const jsonContent = `{
  "api_key": "ab1cdef23ghij4k3lm4nop5q6r7s8tuvwx9y10za",
  "shared_secret": "abcd1ef4ghij5klm6nopqrs7t8uvwxyzabcdefg9"
}`;
    await page.fill('[data-drupal-selector="edit-key-input-settings-key-value"]', jsonContent);
    await page.click('text="Save"');
    await expect(page.getByText('The key conductor has been added.')).toBeVisible();
    await page.goto('/admin/config/services/conductor');
    await page.selectOption('[data-drupal-selector="edit-key-id"]', 'conductor');
    await page.click('text="Save configuration"');
    await expect(
      page.getByText('Successfully established connection to Conductor API'),
    ).toBeVisible();

    await drupal.createRole({ name: 'editor' });
    await drupal.addPermissions({
      role: 'editor',
      permissions: ['create canvas_page', 'edit canvas_page', 'use conductor'],
    });
    await drupal.createUser({
      email: `editor@example.com`,
      username: 'editor',
      password: 'editor',
      roles: ['editor'],
    });
    await drupal.logout();
  } catch (error) {
    // Ensure test-results directory exists
    const screenshotDir = path.join(process.cwd(), 'test-results');
    if (!fs.existsSync(screenshotDir)) {
      fs.mkdirSync(screenshotDir, { recursive: true });
    }

    // Take screenshot with timestamp
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const screenshotPath = path.join(screenshotDir, `playwright-failure-${timestamp}.png`);

    await page.screenshot({ path: screenshotPath, fullPage: true });

    console.log(`Screenshot saved to: ${screenshotPath}`);

    // Re-throw the error so the test still fails
    throw error;
  }
}
