<?php

declare(strict_types=1);

namespace Plugin\tnt_stabila_shop\src\Abstracts;

use ReflectionClass;
use ReflectionProperty;

/**
 * Class AbstractDomainObject
 *
 * @package Plugin\tnt_stabila_shop\src\Abstracts
 */
/**
 * @phpstan-consistent-constructor
 */
abstract class AbstractDomainObject
{
    /**
     * AbstractDomainObject constructor.
     *
     * @param list<string> $modifiedKeys
     */
    public function __construct(public array $modifiedKeys = [])
    {
    }

    /**
     * Will ship an array containing Keys and values of protected and public properties.
     *
     * @param bool $deep
     * @param bool $serialize
     * @return array<string, mixed>
     */
    public function toArray(bool $deep = false, bool $serialize = true): array
    {
        $reflect = new ReflectionClass($this);
        if ($deep === true) {
            $properties = $reflect->getProperties();
        } else {
            $properties = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);
        }
        /** @var array<string, mixed> $toArray */
        $toArray = [];
        foreach ($properties as $property) {
            $propertyName  = $property->getName();
            $propertyValue = $property->getValue($this);
            if ($serialize && (\is_array($propertyValue) || \is_object($propertyValue))) {
                $toArray[$propertyName] = \serialize($propertyValue);
            } else {
                $toArray[$propertyName] = $propertyValue;
            }
        }

        return $toArray;
    }

    /**
     * @param bool $deep
     * @return object
     */
    public function toObject(bool $deep = false): object
    {
        return (object)$this->toArray($deep);
    }

    /**
     * @param bool $deep
     * @param int  $flags
     * @return string
     */
    public function toJson(bool $deep = false, int $flags = JSON_THROW_ON_ERROR): string
    {
        $json = \json_encode($this->toArray($deep), $flags);
        if ($json === false) {
            throw new \RuntimeException('Could not encode domain object to JSON.');
        }

        return $json;
    }

    /**
     * @param array<string, mixed> $newData
     * @return static
     * @description Makes a copy of a readonly domain object while changing the values of the given keys.
     * @comment This is a workaround for the fact that readonly objects cannot be modified. A modified domain object
     *  should never be trusted without further checking.
     * @since 5.3.0
     */
    public function copyWith(array $newData): static
    {
        $asArray = $this->toArray(true);

        foreach ($newData as $key => $value) {
            if (\array_key_exists($key, $asArray) === false) {
                throw new \RuntimeException('Attempting to modify a nonexistent key ('
                    . $key . ') in ' . static::class);
            }
            $asArray[$key] = $value;
        }

        return new static(...$asArray);
    }
}
