<?php

namespace Drupal\Tests\acquia_dam\Functional;

use Drupal\Tests\BrowserTestBase;
use Drupal\user\UserInterface;

/**
 * Functional test for Acquia DAM requirements.
 *
 * @group acquia_dam
 */
class AcquiaDamRequirementsTest extends BrowserTestBase {

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stark';

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'acquia_dam',
    'acquia_dam_test',
  ];

  /**
   * Tests the Acquia DAM connection status on the status report page.
   */
  public function testStatusReport() {
    $this->drupalLogin($this->rootUser);
    $this->drupalGet('/admin/reports/status');
    // Check that the Acquia DAM connection status is not displayed.
    $this->assertSession()->pageTextContains('Acquia DAM');
    $this->assertSession()->pageTextContains('Not configured');
    $this->assertSession()->pageTextContains('No DAM authentication available. Connect this site.');

    // Acquia DAM connection with valid token.
    /** @var \Drupal\Core\Config\ConfigFactoryInterface $configFactory */
    $configFactory = $this->container->get('config.factory');
    $configFactory->getEditable('acquia_dam.settings')
      ->set('domain', 'test.widencollective.com')
      ->save();
    $this->container->get('state')->set(
      'acquia_dam_token',
      $this->randomString()
    );
    // Clear the cache to ensure the status report is updated.
    \Drupal::service('cache.render')->invalidateAll();
    // Reload the status report page.
    $this->drupalGet('/admin/reports/status');
    $this->assertSession()->pageTextContains('Acquia DAM');
    $this->assertSession()->pageTextContains('Connected');
    $this->assertSession()->pageTextContains('Site is successfully authenticated as DAM user: acquia.support@acquia.com.');

    // Acquia DAM connection with expired token.
    $this->container->get('state')->set(
      'acquia_dam_token',
      'expired_token'
    );
    // Clear the cache to ensure the status report is updated.
    \Drupal::service('cache.render')->invalidateAll();
    // Reload the status report page.
    $this->drupalGet('/admin/reports/status');
    $this->assertSession()->pageTextContains('Acquia DAM');
    $this->assertSession()->pageTextContains('Authentication failed');
    $this->assertSession()->pageTextContains('DAM authentication is configured, but authentication failed. Visit the Acquia DAM configuration to re-connect this site.');
  }
}
