<?php

declare(strict_types=1);

namespace Drupal\Tests\block\Kernel;

use Drupal\block\Entity\Block;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\SchemaCheckTestTrait;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;

/**
 * Tests the block config schema.
 */
#[Group('block')]
#[RunTestsInSeparateProcesses]
class BlockConfigSchemaTest extends KernelTestBase {

  use SchemaCheckTestTrait;

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'block',
    'block_content',
    'node',
    // \Drupal\block\Entity\Block->preSave() calls system_region_list().
    'system',
    'taxonomy',
    'user',
    'text',
  ];

  /**
   * The typed config manager.
   *
   * @var \Drupal\Core\Config\TypedConfigManagerInterface
   */
  protected $typedConfig;

  /**
   * The block manager.
   *
   * @var \Drupal\Core\Block\BlockManagerInterface
   */
  protected $blockManager;

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

    $this->typedConfig = \Drupal::service('config.typed');
    $this->blockManager = \Drupal::service('plugin.manager.block');
    $this->installEntitySchema('block_content');
    $this->installEntitySchema('taxonomy_term');
    $this->installEntitySchema('node');
    $this->container->get('theme_installer')->install(['stark']);
  }

  /**
   * Tests the block config schema for block plugins.
   */
  public function testBlockConfigSchema(): void {
    foreach ($this->blockManager->getDefinitions() as $block_id => $definition) {
      // Skip the syndicate block as it is deprecated.
      if ($block_id === 'node_syndicate_block') {
        continue;
      }
      $id = $this->randomMachineName();
      $block = Block::create([
        'id' => $id,
        'theme' => 'stark',
        'weight' => 00,
        'status' => TRUE,
        'region' => 'content',
        'plugin' => $block_id,
        'settings' => [
          'label' => $this->randomMachineName(),
          'provider' => 'system',
          'label_display' => '0',
        ],
        'visibility' => [],
      ]);
      $block->save();

      $config = $this->config("block.block.$id");
      $this->assertEquals($id, $config->get('id'));
      $this->assertConfigSchema($this->typedConfig, $config->getName(), $config->get());
    }
  }

}
