<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\Adapter\PreviewSite;

use Drupal\Core\Entity\EntityStorageException;
use Drupal\preview_site\Entity\PreviewStrategy as ExternalPreviewStrategy;

/**
 * Drupal preview strategy repository.
* */
final class PreviewStrategyRepository implements PreviewStrategyRepositoryInterface {

  /**
   * {@inheritdoc}
   */
  public function getById(string $strategyId): ?PreviewStrategy {
    $existingStrategy = ExternalPreviewStrategy::load($strategyId);
    return $existingStrategy ? new PreviewStrategy($existingStrategy) : NULL;
  }

  /**
   * {@inheritdoc}
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function create(string $strategyId, string $label, string $fileDeploymentPrefix): PreviewStrategy {
    $strategy = ExternalPreviewStrategy::create([
      'id' => $strategyId,
      'label' => $label,
      // Default generation plugin which comes
      // with preview_site (uses Tome module)
      'generate' => 'preview_site_tome',
      // Default deployment plugin which stores
      // generated previews on local file system.
      'deploy' => 'preview_site_public',
      'generateSettings' => [],
      'deploySettings' => ['naming' => $fileDeploymentPrefix],
    ]);

    try {
      $strategy->save();
    } catch (EntityStorageException $e) {
      return $this->getById($strategyId) ?? throw $e;
    }

    return new PreviewStrategy($strategy);
  }

  /**
   * {@inheritdoc}
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function deleteById(string $strategyId): void {
    $strategy = ExternalPreviewStrategy::load($strategyId);
    $strategy?->delete();
  }

}
