<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\Adapter\PreviewSite;

use Drupal\languagewire_translation_provider\Adapter\Entity\EntityInterface;
use Drupal\preview_site\Entity\PreviewSiteBuild as ExternalPreviewSiteBuild;

/**
 * Drupal Preview Site Build Repository.
* */
final class PreviewSiteBuildRepository implements PreviewSiteBuildRepositoryInterface {

  /**
   * {@inheritdoc}
   */
  public function getById(int $buildId): ?PreviewSiteBuild {
    $externalBuild = ExternalPreviewSiteBuild::load($buildId);
    return $externalBuild ? new PreviewSiteBuild($externalBuild) : NULL;
  }

  /**
   * {@inheritdoc}
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function create(EntityInterface $entity, string $label, string $strategyId): ?PreviewSiteBuild {
    $build = ExternalPreviewSiteBuild::create(
        [
          'contents' => [$entity->getEntity()],
          'strategy' => $strategyId,
          'label' => $label,
          'log' => NULL,
          'processed_paths' => ['/'],
        ]
    );
    $build->save();
    return new PreviewSiteBuild($build);
  }

  /**
   * {@inheritdoc}
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function deleteById(int $buildId): void {
    $build = ExternalPreviewSiteBuild::load($buildId);
    $build?->delete();
  }

}
