<?php

declare(strict_types=1);

namespace Drupal\Tests\flowdrop\Unit\Utility;

use Drupal\flowdrop\Utility\NodeAnchor;
use PHPUnit\Framework\TestCase;

/**
 * @coversDefaultClass \Drupal\flowdrop\Utility\NodeAnchor
 *
 * @group flowdrop
 */
final class NodeAnchorTest extends TestCase {

  /**
   * A migrated node resolves its node_type_id anchor.
   *
   * @covers ::read
   */
  public function testReadMigratedNode(): void {
    $node = ['id' => 'calculator.1', 'data' => ['metadata' => ['node_type_id' => 'calculator']]];
    $this->assertSame('calculator', NodeAnchor::read($node));
  }

  /**
   * Migrated metadata resolves its anchor.
   *
   * @covers ::readMetadata
   */
  public function testReadMetadataMigrated(): void {
    $this->assertSame('calculator', NodeAnchor::readMetadata(['node_type_id' => 'calculator']));
  }

  /**
   * A legitimately anchor-less node (e.g. a Note) returns '' without asserting.
   *
   * @covers ::read
   * @covers ::readMetadata
   */
  public function testAnchorlessNodeReturnsEmpty(): void {
    $this->assertSame('', NodeAnchor::readMetadata([]));
    $this->assertSame('', NodeAnchor::read(['id' => 'note.1', 'data' => ['metadata' => []]]));
    $this->assertSame('', NodeAnchor::read(['id' => 'note.1', 'data' => []]));
    $this->assertSame('', NodeAnchor::read(['id' => 'note.1']));
  }

  /**
   * Non-array metadata is treated as anchor-less, not a fatal.
   *
   * @covers ::read
   */
  public function testNonArrayMetadata(): void {
    $this->assertSame('', NodeAnchor::read(['id' => 'x', 'data' => ['metadata' => 'oops']]));
  }

  /**
   * An un-migrated node (legacy `id`, no `node_type_id`) fails loudly.
   *
   * This is the silent-misroute case the assert exists to catch: without the
   * legacy `id` fallback, such a node reads as anchor-less and would slip
   * through callers' "no anchor → skip" guards. The assert turns it into a
   * loud failure wherever assertions are enabled (dev, CI).
   *
   * @covers ::readMetadata
   */
  public function testUnmigratedNodeAssertsLoudly(): void {
    if (!ini_get('zend.assertions') || (int) ini_get('zend.assertions') !== 1) {
      $this->markTestSkipped('Assertions are not enabled in this environment.');
    }
    $this->expectException(\AssertionError::class);
    NodeAnchor::readMetadata(['id' => 'calculator']);
  }

}
