<?php

namespace Drupal\Tests\acquia_contenthub\Kernel;

use Drupal\acquia_contenthub_subscriber\SubscriberTracker;
use Drupal\Tests\acquia_contenthub\Kernel\Core\FileSystemTrait;

/**
 * Tests that files are properly exported and imported.
 *
 * @group acquia_contenthub
 *
 * @package Drupal\Tests\acquia_contenthub\Kernel
 */
class FileImportExportTest extends ImportExportTestBase {

  use FileSystemTrait;

  /**
   * {@inheritdoc}
   */
  protected $fixtures = [
    [
      'cdf' => 'file/node-with-file-reference.json',
      'expectations' => 'expectations/file/reference_1.php',
    ],
    [
      'cdf' => 'file/node-with-multiple-files.json',
      'expectations' => 'expectations/file/reference_2.php',
    ],
    [
      'cdf' => 'file/file-scheme-empty.json',
      'expectations' => 'expectations/file/file_scheme_empty.php',
    ],
    [
      'cdf' => 'file/file-scheme-http.json',
      'expectations' => 'expectations/file/file_scheme_http.php',
    ],
    [
      'cdf' => 'file/file-scheme-https.json',
      'expectations' => 'expectations/file/file_scheme_https.php',
    ],
  ];

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'system',
    'user',
    'node',
    'file',
    'field',
    'depcalc',
    'acquia_contenthub',
    'acquia_contenthub_test',
    'acquia_contenthub_subscriber',
  ];

  /**
   * {@inheritdoc}
   *
   * @throws \Exception
   */
  protected function setup(): void {
    parent::setUp();
    $this->installEntitySchema('user');
    $this->installSchema('user', ['users_data']);
    $this->installSchema('acquia_contenthub_subscriber', [SubscriberTracker::IMPORT_TRACKING_TABLE]);
    $this->installEntitySchema('node');
    $this->fileSystemSetUp();
  }

  /**
   * Tests import/export of node with file.
   *
   * @param int $delta
   *   Delta.
   * @param array $validate_data
   *   Data.
   * @param string $export_type
   *   Entity type ID.
   * @param string $export_uuid
   *   Uuid.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   * @throws \Exception
   *
   * @dataProvider fileImportExportDataProvider
   */
  public function testFileImportExport($delta, array $validate_data, $export_type, $export_uuid) {
    parent::contentEntityImportExport($delta, $validate_data, $export_type, $export_uuid);
    /** @var \Drupal\Core\Entity\EntityRepository $repository */
    $repository = \Drupal::service('entity.repository');
    foreach ($validate_data as $datum) {
      if (!isset($datum['file'])) {
        continue;
      }

      $entity_type = $datum['type'];
      $validate_uuid = $datum['uuid'];
      $file_fixture = $datum['file'];
      $file = $repository->loadEntityByUuid($entity_type, $validate_uuid);
      $this->assertFileExists($file->getFileUri());
      $imported_file_content = file_get_contents($file->getFileUri());
      $this->assertStringEqualsFile(sprintf($file_fixture, $this->getPathToFixtures()), $imported_file_content);
    }
  }

  /**
   * Tests import/export of files with schemes where file copy isn't expected.
   *
   * @param int $delta
   *   Delta.
   * @param array $validate_data
   *   Data.
   * @param string $export_type
   *   Entity type ID.
   * @param string $export_uuid
   *   Uuid.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   * @throws \Exception
   *
   * @dataProvider fileImportExportNoCopyDataProvider
   */
  public function testFileImportExportNoCopy($delta, array $validate_data, $export_type, $export_uuid) {
    // This only asserts that the file entities were created successfully
    // with the expected values. No assertion for the content of the files
    // themselves as files with the given schemes aren't expected to be
    // copied.
    parent::contentEntityImportExport($delta, $validate_data, $export_type, $export_uuid);
  }

  /**
   * Data provider for testFileImportExport.
   *
   * @return array
   *   Test data sets.
   */
  public static function fileImportExportDataProvider(): array {
    $export_uuid_node = [
      'b5ca43f8-adce-411d-a161-aff4eeda5e36',
      '386db454-41ab-4628-b2b1-caae809569a7',
    ];
    $export_uuid_files = [
      'b88f7854-0b14-4993-88ab-f14f9e24c4b3',
      'a5b12985-69f7-46d0-8e3f-a9e940eab99f',
      'f8a90411-8bc0-4e49-a4e5-211add30c654',
    ];

    return [
      [
        0,
        [
          [
            'type' => 'file',
            'uuid' => $export_uuid_files[0],
            'file' => '%s/misc/1.txt',
          ],
        ],
        'node',
        $export_uuid_node['0'],
      ],
      [
        1,
        [
          [
            'type' => 'file',
            'uuid' => $export_uuid_files[1],
            'file' => '%s/misc/1.txt',
          ],
          [
            'type' => 'file',
            'uuid' => $export_uuid_files[2],
            'file' => '%s/misc/2.txt',
          ],
        ],
        'node',
        $export_uuid_node['1'],
      ],
    ];
  }

  /**
   * Data provider for testFileImportExportNoCopy.
   *
   * @return array
   *   Test data sets.
   */
  public static function fileImportExportNoCopyDataProvider(): array {
    $export_uuid_files = [
      '660e1f94-2422-4ccd-af03-6c19abfe62f5',
      '211da662-acec-4d6c-87f6-c1d7b77a098e',
      '5ccc339c-2225-4354-9ae5-82e1244ca434',
    ];

    return [
      [
        2,
        [['type' => 'file', 'uuid' => $export_uuid_files[0]]],
        'file',
        $export_uuid_files[0],
      ],
      [
        3,
        [['type' => 'file', 'uuid' => $export_uuid_files[1]]],
        'file',
        $export_uuid_files[1],
      ],
      [
        4,
        [['type' => 'file', 'uuid' => $export_uuid_files[2]]],
        'file',
        $export_uuid_files[2],
      ],
    ];
  }

  /**
   * Returns path to fixtures directory.
   *
   * @return string
   *   Path to fixtures directory.
   */
  protected function getPathToFixtures() {
    $path_to_fixtures = sprintf('%s/tests/fixtures',
      $this->container->get('module_handler')->getModule('acquia_contenthub')->getPath()
    );
    return $path_to_fixtures;
  }

}
