<?php

declare(strict_types=1);

namespace Drupal\Tests\native_observability_database_observer\Unit\Service;

use Drupal\Tests\UnitTestCase;
use Drupal\native_observability_database_observer\Service\DatabaseQueryClassifier;

/**
 * Covers SQL correlation and hashing helpers.
 */
final class DatabaseQueryClassifierTest extends UnitTestCase {

  /**
   * Verifies that request-bound queries are classified correctly.
   */
  public function testClassifyReturnsRequestBoundWhenCorrelationDataExists(): void {
    $classifier = new DatabaseQueryClassifier();

    $this->assertSame('request_bound', $classifier->classify('req-1', NULL));
    $this->assertSame('request_bound', $classifier->classify(NULL, 'view.frontpage'));
  }

  /**
   * Verifies that missing correlation marks the row as unrelated.
   */
  public function testClassifyReturnsUnrelatedWhenNoCorrelationDataExists(): void {
    $classifier = new DatabaseQueryClassifier();

    $this->assertSame('unrelated', $classifier->classify('', ''));
    $this->assertSame('unrelated', $classifier->classify(NULL, NULL));
  }

  /**
   * Verifies that query hashing is deterministic and uses SHA-256 length.
   */
  public function testBuildQueryHashReturnsStableSha256Hash(): void {
    $classifier = new DatabaseQueryClassifier();

    $sql = 'SELECT * FROM {node} WHERE nid = :nid';
    $hash = $classifier->buildQueryHash($sql);

    $this->assertSame($hash, $classifier->buildQueryHash($sql));
    $this->assertSame(64, strlen($hash));
    $this->assertMatchesRegularExpression('/^[a-f0-9]{64}$/', $hash);
  }

}
