<?php

namespace Drupal\languagewire_translation_provider\Service;

use Drupal\languagewire_translation_provider\Adapter\TMGMT\TmgmtJobInterface;
use Drupal\languagewire_translation_provider\Client\ClientInterface;
use Drupal\languagewire_translation_provider\Domain\Project;
use Drupal\languagewire_translation_provider\Domain\ProjectStatus;
use Psr\Log\LoggerInterface;

/**
 * Project Creator.
 */
class ProjectCreator {

  /**
   * Logger.
   *
   * @var \Psr\Log\LoggerInterface
   */
  private LoggerInterface $logger;

  /**
   * Constructs a new ProjectCreator object.
   *
   * @param \Psr\Log\LoggerInterface $logger
   *   Logger.
   */
  public function __construct(
    LoggerInterface $logger
  ) {
    $this->logger = $logger;
  }

  /**
   * Creates a project in the LanguageWire platform.
   */
  public function createProject(Project &$project, ClientInterface $client, bool $isQuoteOrder = FALSE, bool $shouldCreate = FALSE): void {
    $job = $project->getTmgmtJob();

    try {
      $savedDocuments = $project->getDocuments();

      if ($shouldCreate) {
        $project = $client->submit($project);
      }

      $project->setDocuments($savedDocuments);
      $project->setStatus(ProjectStatus::uploading());

      $correlationID = $project->getCorrelationId();
      $message = "Translation project '$correlationID' was successfully created in the LanguageWire platform.";
      if ($isQuoteOrder) {
        $message = "Translation quote order '$correlationID' was successfully created in the LanguageWire platform.";
      }

      $job->addMessage($message);
    }
    catch (\Exception $exception) {
      $this->logException($exception, $job);
      $message = "Project creation of '{$project->getCorrelationId()}' has failed. Failure reason: {$exception->getMessage()}.";
      $project->setStatus(ProjectStatus::error());
      $job->cancel($message);
      $job->save();
    }
  }

  /**
   * Logs an exception.
   */
  private function logException(\Exception $exception, TmgmtJobInterface $job): void {
    $this->logger->error("Error occurred when trying to create a translation project for job {$job->title()} "
          . "(ID {$job->jobId()}) in the LanguageWire platform. \n"
          . "Error: $exception");
  }

}
