<?php

namespace Drupal\Tests\acquia_contenthub_publisher\Functional\Wizard;

use Drupal\Core\Session\AccountInterface;
use Drupal\Tests\acquia_contenthub\Traits\CommonRandomGenerator;
use Drupal\Tests\views\Functional\Wizard\WizardTestBase;

/**
 * Tests ContentHub Export Tracker View Sort.
 *
 * @group acquia_contenthub_publisher
 */
class ContentHubExportTrackerViewSortTest extends WizardTestBase {

  use CommonRandomGenerator;

  /**
   * User that has administrator permission.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected AccountInterface $authorizedUser;

  /**
   * Path to content hub export tracker view.
   */
  const ACH_EXPORT_TRACKER_VIEW_PATH = 'admin/content/ach_export_tracker';

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

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'file',
    'node',
    'user',
    'views',
    'acquia_contenthub_publisher',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp($import_test_views = TRUE, $modules = []): void {
    parent::setUp();
    $this->authorizedUser = $this->drupalCreateUser(['administer acquia content hub']);
    $this->container->get('config.installer')->installDefaultConfig('module', 'acquia_contenthub_publisher');
    $this->drupalLogin($this->authorizedUser);
    // Inserting test data into tracker table.
    $this->insertDataInTrackerTable();
  }

  /**
   * Tests Content-Hub Export Tracker View Status sort.
   */
  public function testContentHubExportTrackerViewStatusSort(): void {
    $session = $this->assertSession();
    $this->drupalGet('admin/content/ach_export_tracker', ['query' => ['sort' => 'desc', 'order' => 'status']]);
    $session->statusCodeEquals(200);

    $page = $this->getSession()->getPage();
    $rows = $page->findAll('css', 'tr');

    $nodeTypeFound = FALSE;

    foreach ($rows as $row) {
      $entityTypeCell = $row->find('css', '.views-field-status');

      if ($entityTypeCell) {
        $entityTypeText = trim($entityTypeCell->getText());

        if ($entityTypeText === 'ready_to_queue') {
          $nodeTypeFound = TRUE;
        }
        elseif ($entityTypeText === 'queued') {
          $this->assertTrue($nodeTypeFound, 'node_type should come before path_alias');
        }
      }
    }
  }

  /**
   * Tests Content-Hub Export Tracker View Last Modified sort.
   */
  public function testContentHubExportTrackerViewEntityTypeSort(): void {
    $session = $this->assertSession();
    $this->drupalGet('admin/content/ach_export_tracker', ['query' => ['sort' => 'asc', 'order' => 'entity_type']]);
    $session->statusCodeEquals(200);

    $page = $this->getSession()->getPage();
    $rows = $page->findAll('css', 'tr');

    $nodeTypeFound = FALSE;

    foreach ($rows as $row) {
      $entityTypeCell = $row->find('css', '.views-field-entity-type');

      if ($entityTypeCell) {
        $entityTypeText = trim($entityTypeCell->getText());

        if ($entityTypeText === 'node_type') {
          $nodeTypeFound = TRUE;
        }
        elseif ($entityTypeText === 'path_alias') {
          $this->assertTrue($nodeTypeFound, 'node_type should come before path_alias');
        }
      }
    }
  }

  /**
   * Inserts data into the Tracker table.
   */
  protected function insertDataInTrackerTable(): void {
    $data = [
      [
        'entity_uuid' => $this->generateUuid(),
        'entity_type' => 'user_role',
        'status' => 'ready_to_queue',
        'entity_id' => 'ch_export_tracker',
        'label' => 'ch_export_tracker',
      ],
      [
        'entity_uuid' => $this->generateUuid(),
        'entity_type' => 'path_alias',
        'status' => 'exported',
        'entity_id' => '23456',
        'label' => '23456',
      ],
      [
        'entity_uuid' => $this->generateUuid(),
        'entity_type' => 'node_type',
        'status' => 'queued',
        'entity_id' => '1734',
        'label' => '1734',
      ],
    ];
    $query = $this->container->get('database')->insert('acquia_contenthub_publisher_export_tracking');
    foreach ($data as $item) {
      $query->fields(array_keys($item));
      $query->values(array_values($item));
    }
    $query->execute();
  }

}
