<?php

namespace CelerSearch\DataTransfer;

use CelerSearch\Abstracts\RepositoryItem;
use CelerSearch\Utilities\DateTimeUtilities;

/**
 * View configuration DTO
 *
 * Represents a saved search view configuration from the database.
 */
class ViewConfig extends RepositoryItem {

	/**
	 * The view configuration value
	 * @var object
	 */
	protected object $value;

	/**
	 * Constructor
	 * @param object $value
	 */
	public function __construct( object $value ) {
		$this->value = $value;
		if ( isset( $this->value->config ) && is_string( $this->value->config ) ) {
			$this->value->config = json_decode( $this->value->config, true ) ?: [];
		}
	}

	/**
	 * Get the view ID
	 * @return int
	 */
	public function getId(): int {
		return (int) $this->get( 'id' );
	}

	/**
	 * Get the view name
	 * @return string
	 */
	public function getName(): string {
		return $this->get( 'name' ) ?? '';
	}

	/**
	 * Get the view type
	 * @return string
	 */
	public function getType(): string {
		return $this->get( 'type' ) ?? 'search';
	}

	/**
	 * Get the associated index ID
	 * @return int
	 */
	public function getIndexId(): int {
		return (int) $this->get( 'index_id' );
	}

	/**
	 * Get the view configuration array
	 * @return array
	 */
	public function getConfig(): array {
		$config = $this->get( 'config' );
		return is_array( $config ) ? $config : [];
	}

	/**
	 * Get a specific config key
	 * @param string $key
	 * @param mixed $default
	 * @return mixed
	 */
	public function getConfigValue( string $key, $default = null ): mixed {
		$config = $this->getConfig();
		return $config[ $key ] ?? $default;
	}

	/**
	 * Get the created at timestamp
	 * @return null|string
	 */
	public function getCreatedAt(): null|string {
		return $this->get( 'created_at' );
	}

	/**
	 * Get the updated at timestamp
	 * @return null|string
	 */
	public function getUpdatedAt(): null|string {
		return $this->get( 'updated_at' );
	}

	/**
	 * Get a specific key from the view configuration
	 * @param string $key
	 * @return mixed
	 */
	public function get( $key ): mixed {
		return isset( $this->value->$key ) ? $this->value->$key : null;
	}

	/**
	 * Get the full value object
	 * @return object
	 */
	public function getValue(): object {
		return $this->value;
	}

	/**
	 * Get the formatted value object for API responses
	 * @return object
	 */
	public function getFormatted(): object {
		$value = clone $this->value;

		if ( ! empty( $value->created_at ) ) {
			$value->created_at = DateTimeUtilities::format( $value->created_at );
		}
		if ( ! empty( $value->updated_at ) ) {
			$value->updated_at = DateTimeUtilities::format( $value->updated_at );
		}

		return $value;
	}

	/**
	 * Convert to array
	 * @return array
	 */
	public function toArray(): array {
		return (array) $this->value;
	}

	/**
	 * Convert to string
	 * @return string
	 */
	public function __toString(): string {
		return wp_json_encode( $this->value );
	}
}
