<?php

declare(strict_types=1);

namespace Drupal\Tests\farm_ui_dashboard\Functional;

use Drupal\Tests\farm_test\Functional\FarmBrowserTestBase;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;

/**
 * Tests the farmOS dashboard functionality.
 */
#[Group('farm')]
#[RunTestsInSeparateProcesses]
class DashboardTest extends FarmBrowserTestBase {

  /**
   * Test user.
   *
   * @var \Drupal\user\Entity\User|bool
   */
  protected $user;

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

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

    // Create and login a user with necessary permissions.
    $this->user = $this->createUser(['access farm dashboard']);
    $this->drupalLogin($this->user);
  }

  /**
   * Run all tests.
   */
  public function testAll() {
    $this->doTestDashboardBlock();
    $this->doTestDashboardView();
  }

  /**
   * Test that custom blocks are added to the dashboard.
   */
  public function doTestDashboardBlock() {
    $this->drupalGet('/dashboard');
    $this->assertSession()->statusCodeEquals(200);

    // Assert that the test block was not added to the dashboard.
    $this->assertSession()->pageTextNotContains('This is the dashboard test block.');

    // Grant permission to view the block.
    $user = $this->createUser(['access farm dashboard', 'access dashboard test block']);
    $this->drupalLogin($user);

    // Assert that the test block was added to the dashboard.
    $this->drupalGet('/dashboard');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->pageTextContains('This is the dashboard test block.');
  }

  /**
   * Test that custom views are added to the dashboard.
   */
  public function doTestDashboardView() {
    $this->drupalGet('/dashboard');
    $this->assertSession()->statusCodeEquals(200);

    // Assert that the test view was not added to the dashboard.
    $this->assertSession()->pageTextNotContains('User list');
    $this->assertSession()->pageTextNotContains($this->user->getAccountName());

    $user = $this->createUser(['access farm dashboard', 'access user profiles']);
    $this->drupalLogin($user);

    $this->drupalGet('/dashboard');
    $this->assertSession()->statusCodeEquals(200);

    // Assert that the test view was added to the dashboard.
    $this->assertSession()->pageTextContains('User list');
    $this->assertSession()->pageTextContains($user->getAccountName());
  }

}
