<?php

declare(strict_types=1);

namespace Drupal\Tests\user\Kernel;

use Drupal\KernelTests\KernelTestBase;
use Drupal\user\Entity\User;
use Drupal\user\RoleInterface;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\IgnoreDeprecations;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;

/**
 * Tests the user entity class.
 *
 * @see \Drupal\user\Entity\User
 */
#[Group('user')]
#[RunTestsInSeparateProcesses]
class UserEntityTest extends KernelTestBase {

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['system', 'user', 'field'];

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();
    $this->installEntitySchema('user');
  }

  /**
   * Tests some of the methods.
   *
   * @see \Drupal\user\Entity\User::getRoles()
   * @see \Drupal\user\Entity\User::addRole()
   * @see \Drupal\user\Entity\User::removeRole()
   */
  public function testUserMethods(): void {
    $role_storage = $this->container->get('entity_type.manager')->getStorage('user_role');
    $role_storage->create(['id' => 'test_role_one', 'label' => 'Test role 1'])->save();
    $role_storage->create(['id' => 'test_role_two', 'label' => 'Test role 2'])->save();
    $role_storage->create(['id' => 'test_role_three', 'label' => 'Test role 3'])->save();

    $values = [
      'uid' => 1,
      'roles' => ['test_role_one'],
    ];
    $user = User::create($values);

    $this->assertTrue($user->hasRole('test_role_one'));
    $this->assertFalse($user->hasRole('test_role_two'));
    $this->assertEquals([RoleInterface::AUTHENTICATED_ID, 'test_role_one'], $user->getRoles());

    $account = $user->addRole('test_role_one');
    $this->assertSame($user, $account);
    $this->assertTrue($user->hasRole('test_role_one'));
    $this->assertFalse($user->hasRole('test_role_two'));
    $this->assertEquals([RoleInterface::AUTHENTICATED_ID, 'test_role_one'], $user->getRoles());

    $user->addRole('test_role_two');
    $this->assertTrue($user->hasRole('test_role_one'));
    $this->assertTrue($user->hasRole('test_role_two'));
    $this->assertEquals([RoleInterface::AUTHENTICATED_ID, 'test_role_one', 'test_role_two'], $user->getRoles());

    $account = $user->removeRole('test_role_three');
    $this->assertSame($user, $account);
    $this->assertTrue($user->hasRole('test_role_one'));
    $this->assertTrue($user->hasRole('test_role_two'));
    $this->assertEquals([RoleInterface::AUTHENTICATED_ID, 'test_role_one', 'test_role_two'], $user->getRoles());

    $user->removeRole('test_role_one');
    $this->assertFalse($user->hasRole('test_role_one'));
    $this->assertTrue($user->hasRole('test_role_two'));
    $this->assertEquals([RoleInterface::AUTHENTICATED_ID, 'test_role_two'], $user->getRoles());
  }

  /**
   * Tests that all user fields validate properly.
   *
   * @see \Drupal\Core\Field\FieldItemListInterface::generateSampleItems
   * @see \Drupal\Core\Field\FieldItemInterface::generateSampleValue()
   * @see \Drupal\Core\Entity\FieldableEntityInterface::validate()
   */
  public function testUserValidation(): void {
    $user = User::create([]);
    foreach ($user as $field_name => $field) {
      if (!in_array($field_name, ['uid'])) {
        $user->$field_name->generateSampleItems();
      }
    }
    $violations = $user->validate();
    $this->assertFalse((bool) $violations->count());
  }

  /**
   * Tests that ::existingPassword can be used for chaining.
   */
  public function testChainExistingPasswordMethod(): void {
    /** @var \Drupal\user\Entity\User $user */
    $user = User::create([
      'name' => $this->randomMachineName(),
    ]);
    $user = $user->setExistingPassword('existing_pass');
    $this->assertInstanceOf(User::class, $user);
  }

  /**
   * Tests that accessing the password property is correctly deprecated.
   */
  #[IgnoreDeprecations]
  public function testPasswordProperty(): void {
    /** @var \Drupal\user\Entity\User $user */
    $user = User::create([
      'name' => $this->randomMachineName(),
    ]);

    $user->password = 'password';

    $this->expectUserDeprecationMessage('Getting the password property is deprecated in drupal:11.4.0 and is removed from drupal:12.0.0. See https://www.drupal.org/node/3569185');
    $this->assertEquals('password', $user->password);
  }

  /**
   * Tests that ::getLastAccessedTime() returns an integer for a loaded user.
   *
   * @legacy-covers ::getLastAccessedTime
   */
  public function testGetLastAccessedTime(): void {
    $access = 100;
    /** @var \Drupal\user\Entity\User $user */
    $user = User::create([
      'name' => $this->randomMachineName(),
      'access' => $access,
    ]);
    $id = $user->save();

    $loaded_user = User::load($id);
    $this->assertSame($access, $loaded_user->getLastAccessedTime());
  }

}
