<?php
/**
 * Dry-run operation projection.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChanges\Validation;

use ScheduledChanges\Domain\Operation\Operation;

/**
 * Redacted intended write shown without invoking provider mutation methods.
 */
final class DryRunOperation {
	private string $uuid;
	private string $type;
	private string $targetReference;
	private ?string $fieldPath;
	private string $providerId;
	/**
	 * @var mixed
	 */
	private $before;
	/**
	 * @var mixed
	 */
	private $after;
	private string $summary;
	/**
	 * @param mixed $before
	 * @param mixed $after
	 */
	private function __construct( string $uuid, string $type, string $targetReference, ?string $fieldPath, string $providerId, $before, $after, string $summary ) {
		$this->uuid            = $uuid;
		$this->type            = $type;
		$this->targetReference = $targetReference;
		$this->fieldPath       = $fieldPath;
		$this->providerId      = $providerId;
		$this->before          = $before;
		$this->after           = $after;
		$this->summary         = $summary;
	}

	public static function fromOperation( Operation $operation ): self {
		$sensitive = true === ( $operation->redactionRules()['sensitive'] ?? false );

		return new self(
			$operation->uuid()->value(),
			$operation->type(),
			$operation->targetReference(),
			$operation->fieldPath(),
			$operation->providerId(),
			$sensitive ? '[redacted]' : $operation->before(),
			$sensitive ? '[redacted]' : $operation->after(),
			$operation->summary()
		);
	}

	/**
	 * @return array<string,mixed>
	 */
	public function toArray(): array {
		return array(
			'uuid'             => $this->uuid,
			'type'             => $this->type,
			'target_reference' => $this->targetReference,
			'field_path'       => $this->fieldPath,
			'provider_id'      => $this->providerId,
			'before'           => $this->before,
			'after'            => $this->after,
			'summary'          => $this->summary,
		);
	}
}
