<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\Platform\Document;

use Drupal\languagewire_translation_provider\api\Core\Exception\NonRecoverableError;
use Drupal\languagewire_translation_provider\Domain\Document;
use Drupal\languagewire_translation_provider\Domain\DocumentStatus;

/**
 * Invalid Document.
 */
final class InvalidDocument extends DocumentBase {

  /**
   * Document.
   *
   * @var \Drupal\languagewire_translation_provider\Domain\Document
   */
  protected Document $document;

  /**
   * Reason.
   *
   * @var string
   */
  private string $reason;

  /**
   * Constructs a new InvalidDocument object.
   *
   * @param \Drupal\languagewire_translation_provider\Domain\Document $document
   *   Document.
   * @param string $reason
   *   Reason.
   */
  public function __construct(Document $document, string $reason) {
    parent::__construct($document);
    $this->document = $document;
    $this->reason = $reason;
  }

  /**
   * From Upload Exception.
   */
  public static function fromUploadException(\Exception $exception, Document $document): self {
    $documentTitle = $document->getTitle();
    $reason = "Could not upload \"$documentTitle\" item to LanguageWire platform: {$exception->getMessage()}.";

    if ($exception instanceof NonRecoverableError) {
      $reason = "Cannot upload \"$documentTitle\" item to the LanguageWire platform: {$exception->getMessage()}";
    }

    return new self($document, $reason);
  }

  /**
   * From Requesting Validation Exception.
   */
  public static function fromRequestingValidationException(Document $document): self {
    $documentTitle = $document->getTitle();
    $reason = "Could not start item validation \"$documentTitle\" at the LanguageWire platform.";
    return new self($document, $reason);
  }

  /**
   * Get Reason.
   */
  public function getReason(): string {
    return $this->reason;
  }

  /**
   * Update Domain Document.
   */
  public function updateDomainDocument(): void {
    $this->document->addError($this->reason);
    $this->document->setStatus(DocumentStatus::error());
  }

}
