<?php
/**
 * Recording workspace creation result.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChanges\Recording;

/**
 * Provider-owned workspace details persisted with a recording session.
 *
 * @phpstan-import-type RecordingRelationMap from RecordingWorkspaceAdapter
 * @phpstan-import-type RecordingProviderMap from RecordingWorkspaceAdapter
 */
final class RecordingWorkspaceResult {
	private int $workspace_id;
	/**
	 * @var array<string,mixed>
	 * @phpstan-var RecordingRelationMap
	 */
	private array $relation_map;
	/**
	 * @var array<string,mixed>
	 * @phpstan-var RecordingProviderMap
	 */
	private array $provider_map;

	/**
	 * @param array<string,mixed> $relation_map Source/workspace relationship map.
	 * @param array<string,mixed> $provider_map Provider workspace metadata.
	 * @phpstan-param RecordingRelationMap $relation_map
	 * @phpstan-param RecordingProviderMap $provider_map
	 */
	public function __construct( int $workspace_id, array $relation_map = array(), array $provider_map = array() ) {
		if ( $workspace_id <= 0 ) {
			throw new \InvalidArgumentException( 'Recording workspace ID must be positive.' );
		}

		$this->workspace_id = $workspace_id;
		$this->relation_map = $relation_map;
		$this->provider_map = $provider_map;
	}

	public function workspaceId(): int {
		return $this->workspace_id;
	}

	/**
	 * @return array<string,mixed>
	 * @phpstan-return RecordingRelationMap
	 */
	public function relationMap(): array {
		return $this->relation_map;
	}

	/**
	 * @return array<string,mixed>
	 * @phpstan-return RecordingProviderMap
	 */
	public function providerMap(): array {
		return $this->provider_map;
	}

	public function workspaceProviderId(): string {
		return $this->requiredProviderString( 'workspace_provider_id' );
	}

	public function workspaceType(): string {
		return $this->requiredProviderString( 'workspace_type' );
	}

	public function workspaceReference(): string {
		return $this->requiredProviderString( 'workspace_reference' );
	}

	private function requiredProviderString( string $key ): string {
		$value = trim( (string) ( $this->provider_map[ $key ] ?? '' ) );

		if ( '' === $value ) {
			throw new \RuntimeException( 'Recording workspace result is missing ' . esc_html( $key ) . '.' );
		}

		return $value;
	}
}
