<?php

namespace CelerSearch\DataTransfer;

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

class ServiceConfig extends RepositoryItem {

	protected object $value;

	public function __construct( object $value ) {
		$this->value = $value;
		if ( isset( $this->value->config ) && is_array( $this->value->config ) ) {
			$this->value->config = (object) $this->value->config;
		}
	}

	public function getId(): int {
		return $this->get( 'id' );
	}

	public function getName(): string {
		return $this->get( 'name' );
	}

	public function getProvider(): string {
		return $this->get( 'provider' );
	}

	public function getConfig(): null|object {
		return $this->get( 'config' );
	}

	public function getStatus(): null|string {
		return $this->get( 'status' );
	}

	public function getCheckedAt(): null|string {
		return $this->get( 'checked_at' );
	}

	public function getCreatedAt(): null|string {
		return $this->get( 'created_at' );
	}

	public function getFailureCount(): int {
		return (int) $this->get( 'failure_count' );
	}

	public function get( $key ): mixed {
		return isset( $this->value->$key ) ? $this->value->$key : null;
	}

	public function getValue() {
		return $this->value;
	}

	public function getFormatted() {
		$value = $this->value;

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

	}


	public function __toString(): string {
		return json_encode( $this->value );
	}

	public function toArray(): array {
		return (array) $this->value;
	}

}