<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\Database\Mapper;

use Drupal\languagewire_translation_provider\Adapter\TMGMT\JobRepositoryInterface;
use Drupal\languagewire_translation_provider\Database\DocumentRepositoryInterface;
use Drupal\languagewire_translation_provider\Domain\Project;
use Drupal\languagewire_translation_provider\Domain\ProjectStatus;
use Laminas\Diactoros\Uri;

/**
 * Project Mapper.
 * */
class ProjectMapper {

  /**
   * TMGMT job repository.
   *
   * @var \Drupal\languagewire_translation_provider\Adapter\TMGMT\JobRepositoryInterface
   */
  private JobRepositoryInterface $tmgmtJobRepository;

  /**
   * Document repository.
   *
   * @var \Drupal\languagewire_translation_provider\Database\DocumentRepositoryInterface
   */
  private DocumentRepositoryInterface $documentRepository;

  /**
   * Constructs a new ProjectMapper object.
   *
   * @param \Drupal\languagewire_translation_provider\Adapter\TMGMT\JobRepositoryInterface $tmgmtJobRepository
   *   TMGMT job repository.
   * @param \Drupal\languagewire_translation_provider\Database\DocumentRepositoryInterface $documentRepository
   *   Document repository.
   */
  public function __construct(JobRepositoryInterface $tmgmtJobRepository, DocumentRepositoryInterface $documentRepository) {
    $this->tmgmtJobRepository = $tmgmtJobRepository;
    $this->documentRepository = $documentRepository;
  }

  /**
   * To project.
   */
  public function toProject(array $projectDto): ?Project {
    try {
      $projectId = isset($projectDto['pid']) ? (int) $projectDto['pid'] : NULL;
      return new Project(
        $this->tmgmtJobRepository->getById((int) $projectDto['tmgmt_job_id']),
        $projectDto['correlation_id'],
        new ProjectStatus($projectDto['status']),
        $projectId ? $this->documentRepository->getAllByProjectId($projectId) : [],
        $projectId,
        isset($projectDto['platform_id']) ? (int) $projectDto['platform_id'] : 0,
        new Uri((string) ($projectDto['platform_url'] ?? '')),
        $projectDto['bundle_id']
      );
    }
    catch (\Throwable) {
      return NULL;
    }
  }

  /**
   * To database entity.
   */
  public function toDatabaseEntity(Project $project): array {
    return [
      'correlation_id' => $project->getCorrelationId(),
      'tmgmt_job_id' => $project->getTmgmtJob()->jobId(),
      'status' => $project->getStatus()->value(),
      'platform_id' => $project->getPlatformId(),
      'platform_url' => (string) $project->getPlatformUrl(),
      'bundle_id' => (string) $project->getBundlingId(),
    ];
  }

}
