<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\Domain;

use Drupal\languagewire_translation_provider\Adapter\Database\DocumentRepository;
use Drupal\languagewire_translation_provider\Adapter\TMGMT\TmgmtJob;
use Drupal\languagewire_translation_provider\api\Helpers\Strings;

/**
 * Project manager.
 */
final class ProjectManager {

  /**
   * Constructs a new Project manager.
   *
   * @param \Drupal\languagewire_translation_provider\Adapter\Database\DocumentRepository $documentRepository
   *   Document repository.
   */
  public function __construct(
    private DocumentRepository $documentRepository
  ) {}

  /**
   * Create project from job.
   *
   * @throws \Random\RandomException
   */
  public function createProjectFromJob(TmgmtJob $job, ?string $bundlingId): Project {
    return new Project(
      $job,
      Strings::uuid4(),
      ProjectStatus::underCreation(),
      [],
      NULL,
      0,
      NULL,
      $bundlingId
    );
  }

  /**
   * Split job items.
   *
   * @throws \Drupal\tmgmt\TMGMTException
   */
  public function splitJobIntoItemsChucks(TmgmtJob $job): array {
    $maxDocumentsPerProject = $job->translator()->getMaxDocumentsPerProject();

    return array_chunk($job->items(), $maxDocumentsPerProject);
  }

  /**
   * Save items to project.
   *
   * @throws \Exception
   */
  public function saveItemsToProject(Project $project, array $items): void {
    $documents = DocumentFactory::createDocumentsForTmgmtJobItems($items, $project->getId());
    $this->documentRepository->saveMany($documents);
  }

}
