<?php

declare(strict_types=1);

namespace Drupal\sobki_assets\Service;

use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\sobki_assets\Form\AssetsUploadForm;

/**
 * A helper service to purge the destination directory.
 */
class DestinationDirectoryPurger implements DestinationDirectoryPurgerInterface {

  /**
   * Constructor.
   */
  public function __construct(
    protected EntityTypeManagerInterface $entityTypeManager,
    protected CacheTagsInvalidatorInterface $cacheTagsInvalidator,
    protected FileSystemInterface $fileSystem,
  ) {}

  /**
   * {@inheritdoc}
   */
  public function purge(?string $fid = NULL): void {
    $fileStorage = $this->entityTypeManager->getStorage('file');
    $query = $fileStorage->getQuery()
      ->accessCheck(FALSE)
      ->condition('uri', AssetsUploadForm::DESTINATION_DIRECTORY . '/%', 'LIKE');
    if ($fid) {
      $query->condition('fid', $fid, '!=');
    }
    $fids = $query->execute();
    $files = $fileStorage->loadMultiple($fids);
    $fileStorage->delete($files);
    $this->cacheTagsInvalidator->invalidateTags([static::ASSETS_CACHE_TAG]);
  }

  /**
   * {@inheritdoc}
   */
  public function removeEmptyDestinationDirectory(): void {
    $files = $this->fileSystem->scanDirectory(AssetsUploadForm::DESTINATION_DIRECTORY, '/.*/');

    if (empty($files)) {
      $this->fileSystem->deleteRecursive(AssetsUploadForm::DESTINATION_DIRECTORY);
    }
  }

}
