<?php

namespace CouponsPlus\App\Coupon\Tree\Data\Transformers;

use JsonException;
use CouponsPlus\App\Coupon\Tree\Data\Transformers\Abilities\DataTransformer;
use Dflydev\DotAccessData\Data;

class MergeBaseTestableIntoTestablePartialTransformer implements DataTransformer
{
    protected object $testableBase;

    /**
     * @param object $testableBase
     */
    public function __construct(object $testableBase)
    {
        $this->testableBase = $testableBase;
    }

    /**
     * @param object $data The testable partial
     */
    public function transform($data) : object
    {
        $baseTestableArray = json_decode(
            json_encode($this->testableBase, JSON_THROW_ON_ERROR),
            true,
            512,
            JSON_THROW_ON_ERROR
        );
        $partialTestableArray = json_decode(json_encode($data, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR);

        // Create Data objects for merging
        $baseTestableData = new Data($baseTestableArray);
        $partialTestableData = new Data($partialTestableArray);

        // Merge the data (this overwrites values like lodash.merge)
        $baseTestableData->import($partialTestableData->export());

        return json_decode(
            json_encode(
                array_merge(
                    (array)$data,
                    $baseTestableData->export()
                ),
                JSON_THROW_ON_ERROR
            ), false, 512, JSON_THROW_ON_ERROR);
    }
}