<?php

declare(strict_types=1);

namespace Drupal\eb\Entity;

use Drupal\Core\Entity\Attribute\ContentEntityType;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\ContentEntityDeleteForm;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\eb\Access\EbRollbackAccessControlHandler;
use Drupal\eb\EbRollbackListBuilder;
use Drupal\user\EntityOwnerTrait;
use Drupal\views\EntityViewsData;

/**
 * Defines the EbRollback content entity.
 *
 * Represents a single definition application that can be rolled back.
 * Contains multiple EbRollbackOperation entities.
 */
#[ContentEntityType(
  id: 'eb_rollback',
  label: new TranslatableMarkup('Rollback'),
  label_collection: new TranslatableMarkup('Rollbacks'),
  label_singular: new TranslatableMarkup('rollback'),
  label_plural: new TranslatableMarkup('rollbacks'),
  entity_keys: [
    'id' => 'id',
    'uuid' => 'uuid',
    'label' => 'label',
    'owner' => 'uid',
  ],
  handlers: [
    'storage' => SqlContentEntityStorage::class,
    'access' => EbRollbackAccessControlHandler::class,
    'list_builder' => EbRollbackListBuilder::class,
    'views_data' => EntityViewsData::class,
    'form' => [
      'delete' => ContentEntityDeleteForm::class,
    ],
  ],
  links: [
    'collection' => '/admin/config/development/eb/rollback',
    'canonical' => '/admin/config/development/eb/rollback/{eb_rollback}',
    'delete-form' => '/admin/config/development/eb/rollback/{eb_rollback}/delete',
  ],
  admin_permission: 'administer entity builder',
  base_table: 'eb_rollback',
)]
class EbRollback extends ContentEntityBase implements EbRollbackInterface {

  use EntityChangedTrait;
  use EntityOwnerTrait;

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type): array {
    $fields = parent::baseFieldDefinitions($entity_type);
    $fields += static::ownerBaseFieldDefinitions($entity_type);

    $fields['definition_id'] = BaseFieldDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Definition ID'))
      ->setDescription(new TranslatableMarkup('The source definition ID.'))
      ->setSetting('max_length', 128)
      ->setRequired(FALSE);

    $fields['label'] = BaseFieldDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Label'))
      ->setDescription(new TranslatableMarkup('The rollback label.'))
      ->setSetting('max_length', 255)
      ->setRequired(TRUE);

    $fields['status'] = BaseFieldDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Status'))
      ->setDescription(new TranslatableMarkup('The rollback status.'))
      ->setSetting('max_length', 32)
      ->setDefaultValue('pending');

    $fields['operation_count'] = BaseFieldDefinition::create('integer')
      ->setLabel(new TranslatableMarkup('Operation Count'))
      ->setDescription(new TranslatableMarkup('Total number of operations.'))
      ->setDefaultValue(0);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(new TranslatableMarkup('Created'))
      ->setDescription(new TranslatableMarkup('The time the rollback was created.'));

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(new TranslatableMarkup('Changed'))
      ->setDescription(new TranslatableMarkup('The time the rollback was last updated.'));

    $fields['completed'] = BaseFieldDefinition::create('timestamp')
      ->setLabel(new TranslatableMarkup('Completed'))
      ->setDescription(new TranslatableMarkup('The time the rollback was executed.'));

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getDefinitionId(): ?string {
    return $this->get('definition_id')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setDefinitionId(string $definitionId): self {
    $this->set('definition_id', $definitionId);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getStatus(): string {
    return $this->get('status')->value ?? 'pending';
  }

  /**
   * {@inheritdoc}
   */
  public function setStatus(string $status): self {
    $this->set('status', $status);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getOperationCount(): int {
    return (int) $this->get('operation_count')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setOperationCount(int $count): self {
    $this->set('operation_count', $count);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getCompletedTime(): ?int {
    $value = $this->get('completed')->value;
    return $value !== NULL ? (int) $value : NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function setCompletedTime(int $timestamp): self {
    $this->set('completed', $timestamp);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isPending(): bool {
    return $this->getStatus() === 'pending';
  }

  /**
   * {@inheritdoc}
   */
  public function isCompleted(): bool {
    return $this->getStatus() === 'completed';
  }

}
