<?php

namespace Drupal\Tests\acquia_contenthub_publisher\Unit;

use Drupal\acquia_contenthub\Libs\Logging\ContentHubEventLogger;
use Drupal\acquia_contenthub_publisher\ContentHubExportLogger;
use Drupal\Tests\acquia_contenthub\Unit\Helpers\LoggerMock;
use Drupal\Tests\UnitTestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;

/**
 * ContentHubExportErrorLoggingTest tests event logging for export failures.
 *
 * @group acquia_contenthub_publisher
 *
 * @package Drupal\Tests\acquia_contenthub_publisher
 *
 * @coversDefaultClass \Drupal\acquia_contenthub_publisher\ContentHubExportLogger
 */
class ContentHubExportErrorLoggingTest extends UnitTestCase {

  use ProphecyTrait;

  /**
   * Logger mock.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $loggerMock;

  /**
   * CH event logger.
   *
   * @var \Drupal\acquia_contenthub\Libs\Logging\ContentHubEventLogger
   */
  protected $eventLogger;

  /**
   * SUT.
   *
   * @var \Drupal\acquia_contenthub_publisher\ContentHubExportLogger
   */
  protected $contentHubExportLogger;

  /**
   * Used for mocking event logging.
   *
   * @var string
   */
  public static $logMessage = '';

  /**
   * {@inheritDoc}
   */
  public function setUp(): void {
    parent::setUp();
    $this->loggerMock = new LoggerMock();
    $this->eventLogger = $this->prophesize(ContentHubEventLogger::class);
    $this->eventLogger
      ->logEntityEvent(Argument::any(), Argument::any(), Argument::any(), Argument::any())
      ->will(function ($arguments) {
        ContentHubExportErrorLoggingTest::$logMessage = $arguments[1];
      }
      );
    $this->contentHubExportLogger = new ContentHubExportLogger($this->loggerMock, $this->eventLogger->reveal());
  }

  /**
   * Tests whether logging is failed.
   *
   * @covers ::logError
   */
  public function testFailureEventLogging(): void {
    $message = 'Entity: @entity_type - @uuid. Error: @error';
    $context = [
      '@entity_type' => 'Node',
      '@uuid' => 'some-uuid',
    ];
    // @todo Can be removed after we support php8 or higher.
    if (version_compare(phpversion(), '8', '>=')) {
      $this->expectException(\ValueError::class);
      $this->expectExceptionMessage('The arguments array must contain 3 items, 2 given');
      $this->contentHubExportLogger->logError($message, $context);
    }
  }

  /**
   * Tests successful event logging.
   *
   * @covers ::logError
   */
  public function testSuccessfulEventLogging(): void {
    $message = 'Entity: @entity_type - @uuid. Error: @error';
    $context = [
      '@entity_type' => 'Node',
      '@uuid' => 'some-uuid',
      '@error' => 'error in export',
    ];
    $this->contentHubExportLogger->logError($message, $context);
    $error_messages = $this->loggerMock->getErrorMessages();
    $msg = 'Entity: Node - some-uuid. Error: error in export';
    $this->assertEquals($msg, $error_messages[0]);
    $this->assertEquals($msg, self::$logMessage);
  }

}
