<?php

declare(strict_types=1);

namespace Drupal\Tests\field\Unit;

use Drupal\Component\Uuid\UuidInterface;
use Drupal\Core\Config\Entity\ConfigEntityTypeInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldException;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\FieldTypePluginManagerInterface;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\UnitTestCase;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;

/**
 * Tests Drupal\field\Entity\FieldStorageConfig.
 */
#[CoversClass(FieldStorageConfig::class)]
#[Group('field')]
class FieldStorageConfigEntityUnitTest extends UnitTestCase {

  /**
   * The entity type manager used for testing.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface|\PHPUnit\Framework\MockObject\Stub
   */
  protected $entityTypeManager;

  /**
   * The UUID generator used for testing.
   *
   * @var \Drupal\Component\Uuid\UuidInterface|\PHPUnit\Framework\MockObject\Stub
   */
  protected $uuid;

  /**
   * The field type manager.
   *
   * @var \Drupal\Core\Field\FieldTypePluginManagerInterface|\PHPUnit\Framework\MockObject\MockObject
   */
  protected $fieldTypeManager;

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

    $this->entityTypeManager = $this->createStub(EntityTypeManagerInterface::class);
    $this->uuid = $this->createStub(UuidInterface::class);
    $this->fieldTypeManager = $this->createMock(FieldTypePluginManagerInterface::class);

    $container = new ContainerBuilder();
    $container->set('entity_type.manager', $this->entityTypeManager);
    $container->set('uuid', $this->uuid);
    $container->set('plugin.manager.field.field_type', $this->fieldTypeManager);
    \Drupal::setContainer($container);
  }

  /**
   * Tests calculate dependencies.
   */
  public function testCalculateDependencies(): void {
    // Create a mock entity type for FieldStorageConfig.
    $fieldStorageConfigentityType = $this->createStub(ConfigEntityTypeInterface::class);
    $fieldStorageConfigentityType
      ->method('getProvider')
      ->willReturn('field');

    // Create a mock entity type to attach the field to.
    $attached_entity_type_id = $this->randomMachineName();
    $attached_entity_type = $this->createStub(EntityTypeInterface::class);
    $attached_entity_type
      ->method('getProvider')
      ->willReturn('entity_provider_module');

    // Get definition is called three times. Twice in
    // ConfigEntityBase::addDependency() to get the provider of the field config
    // entity type and once in FieldStorageConfig::calculateDependencies() to
    // get the provider of the entity type that field is attached to.
    $this->entityTypeManager
      ->method('getDefinition')
      ->willReturnMap([
        ['field_storage_config', TRUE, $fieldStorageConfigentityType],
        [$attached_entity_type_id, TRUE, $attached_entity_type],
      ]);

    $this->fieldTypeManager->expects($this->atLeastOnce())
      ->method('getDefinition')
      ->with('test_field_type', FALSE)
      ->willReturn([
        'class' => TestFieldType::class,
      ]);

    $field_storage = new FieldStorageConfig([
      'entity_type' => $attached_entity_type_id,
      'field_name' => 'test_field',
      'type' => 'test_field_type',
      'module' => 'test_module',
    ]);

    $dependencies = $field_storage->calculateDependencies()->getDependencies();
    $this->assertEquals(['entity_provider_module', 'entity_test', 'test_module'], $dependencies['module']);
    $this->assertEquals(['stark'], $dependencies['theme']);
  }

  /**
   * Tests stored cardinality.
   *
   * @legacy-covers ::getCardinality
   */
  public function testStoredCardinality(): void {
    $this->fieldTypeManager->expects($this->atLeastOnce())
      ->method('getDefinition')
      ->with('test_field_type')
      ->willReturn([
        'class' => TestFieldType::class,
        // The field type definition has no enforced cardinality.
        'cardinality' => NULL,
      ]);

    $field_storage = new FieldStorageConfig([
      'entity_type' => 'entity_test',
      'field_name' => 'test_field',
      'type' => 'test_field_type',
      'module' => 'test_module',
    ]);
    $field_storage->setCardinality(8);

    // Check that the stored cardinality is returned.
    $this->assertEquals(8, $field_storage->getCardinality());
  }

  /**
   * Tests enforced cardinality.
   *
   * @legacy-covers ::getCardinality
   */
  public function testEnforcedCardinality(): void {
    $this->fieldTypeManager->expects($this->atLeastOnce())
      ->method('getDefinition')
      ->with('test_field_type')
      ->willReturn([
        'class' => TestFieldType::class,
        // This field type defines an enforced cardinality.
        'cardinality' => 21,
      ]);

    $field_storage = new FieldStorageConfig([
      'entity_type' => 'entity_test',
      'field_name' => 'test_field',
      'type' => 'test_field_type',
      'module' => 'test_module',
    ]);
    // Custom cardinality tentative.
    $field_storage->setCardinality(8);

    // Check that the enforced cardinality is returned.
    $this->assertEquals(21, $field_storage->getCardinality());
  }

  /**
   * Tests invalid enforced cardinality.
   *
   * @param mixed $enforced_cardinality
   *   Enforced cardinality.
   *
   * @legacy-covers ::getCardinality
   */
  #[DataProvider('providerInvalidEnforcedCardinality')]
  public function testInvalidEnforcedCardinality(int|string $enforced_cardinality): void {
    $this->fieldTypeManager->expects($this->atLeastOnce())
      ->method('getDefinition')
      ->with('test_field_type')
      ->willReturn([
        'class' => TestFieldType::class,
        'cardinality' => $enforced_cardinality,
      ]);

    $field_storage = new FieldStorageConfig([
      'entity_type' => 'entity_test',
      'field_name' => 'test_field',
      'type' => 'test_field_type',
      'module' => 'test_module',
    ]);

    $this->expectException(FieldException::class);
    $this->expectExceptionMessage("Invalid enforced cardinality '$enforced_cardinality'. Allowed values: a positive integer or -1.");
    $field_storage->getCardinality();
  }

  /**
   * Data provider for ::testInvalidEnforcedCardinality()
   *
   * @return array
   *   Test cases.
   */
  public static function providerInvalidEnforcedCardinality(): array {
    return [
      'zero' => [0],
      'negative_other_than_-1' => [-70],
      'non_numeric' => ['abc%$#@!'],
    ];
  }

}

/**
 * A test class to test field storage dependencies.
 *
 * @see \Drupal\Core\Field\FieldItemInterface::calculateStorageDependencies()
 */
class TestFieldType {

  /**
   * {@inheritdoc}
   */
  public static function calculateStorageDependencies(FieldStorageDefinitionInterface $field_definition): array {
    $dependencies = [];
    $dependencies['module'] = ['entity_test'];
    $dependencies['theme'] = ['stark'];

    return $dependencies;
  }

}
