<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\Database\Mapper;

use Drupal\languagewire_translation_provider\Adapter\TMGMT\JobItemRepositoryInterface;
use Drupal\languagewire_translation_provider\Domain\Document;
use Drupal\languagewire_translation_provider\Domain\DocumentStatus;
use function json_decode;
use function json_encode;

/**
 * Document Mapper.
 * */
class DocumentMapper {
  /**
   * Job item repository.
   *
   * @var \Drupal\languagewire_translation_provider\Adapter\TMGMT\JobItemRepositoryInterface
   */
  private JobItemRepositoryInterface $jobItemRepository;

  /**
   * Constructs a new DocumentMapper object.
   *
   * @param \Drupal\languagewire_translation_provider\Adapter\TMGMT\JobItemRepositoryInterface $jobItemRepository
   *   Job item repository.
   */
  public function __construct(JobItemRepositoryInterface $jobItemRepository) {
    $this->jobItemRepository = $jobItemRepository;
  }

  /**
   * To document.
   */
  public function toDocument(array $documentDto): ?Document {
    try {
      return new Document((int) $documentDto['project_id'], $this->jobItemRepository->getById((int) $documentDto['tmgmt_item_id']), new DocumentStatus($documentDto['status']), isset($documentDto['did']) ? (int) $documentDto['did'] : NULL, $documentDto['platform_id'] ?? NULL, isset($documentDto['errors']) ? json_decode($documentDto['errors'], TRUE) : []);
    }
    catch (\Throwable) {
      return NULL;
    }
  }

  /**
   * To database entity.
   */
  public function toDatabaseEntity(Document $document): array {
    return [
      'project_id' => $document->getProjectId(),
      'tmgmt_item_id' => $document->getTmgmtItem()->itemId(),
      'status' => $document->getStatus()->value(),
      'platform_id' => $document->getPlatformId(),
      'errors' => json_encode($document->getErrors()),
    ];
  }

}
