<?php

namespace Drupal\Tests\api_monitor_client\Functional;

use Drupal\Tests\BrowserTestBase;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;

/**
 * Tests the status page of the API Monitor Client.
 */
#[Group('api_monitor')]
#[RunTestsInSeparateProcesses]
class StatusPageTest extends BrowserTestBase {

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['api_monitor_client'];

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

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();

    $admin_user = $this->drupalCreateUser([
      'administer site configuration',
    ]);
    $this->drupalLogin($admin_user);

    // Insert dummy data into the database.
    $database = $this->container->get('database');
    $database->insert('api_monitor_history')
      ->fields([
        'api_id' => 'test_api',
        'api_name' => 'Unit Test API',
        'status_code' => 200,
        'response_time' => 150.5,
        'timestamp' => time(),
        'success' => 1,
      ])
      ->execute();
  }

  /**
   * Tests the status page table and operations.
   */
  public function testStatusPage() {
    $this->drupalGet('/admin/api-status');
    $assert_session = $this->assertSession();

    $assert_session->statusCodeEquals(200);
    $assert_session->pageTextContains('Servizi API Status');
    $assert_session->pageTextContains('Unit Test API');
    $assert_session->pageTextContains('200');
    $assert_session->pageTextContains('150.5ms');

    // Check for the "Operations" column.
    $assert_session->elementExists('css', 'th:contains("Operations")');

    // Check that the dropbutton (operations) is present.
    $assert_session->elementExists('css', 'ul.dropbutton');
    $assert_session->linkExists('Dettaglio');
    $assert_session->linkExists('Swagger');

    // Verify links.
    $assert_session->linkByHrefExists('/admin/reports/api-monitor/test_api');
    $assert_session->linkByHrefExists('/admin/api-monitor/swagger/test_api');
  }

}
