<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\DocStoreBundle\Service;

use Chill\DocStoreBundle\Entity\StoredObjectVersion;
use Psr\Log\LoggerInterface;

/**
 * Class responsible for restoring stored object versions into the same stored object.
 */
final readonly class StoredObjectRestore implements StoredObjectRestoreInterface
{
    public function __construct(private readonly StoredObjectManagerInterface $storedObjectManager, private readonly LoggerInterface $logger) {}

    public function restore(StoredObjectVersion $storedObjectVersion): StoredObjectVersion
    {
        $oldContent = $this->storedObjectManager->read($storedObjectVersion);

        $newVersion = $this->storedObjectManager->write($storedObjectVersion->getStoredObject(), $oldContent, $storedObjectVersion->getType());

        $newVersion->setCreatedFrom($storedObjectVersion);

        $this->logger->info('[StoredObjectRestore] Restore stored object version', [
            'stored_object_uuid' => $storedObjectVersion->getStoredObject()->getUuid(),
            'old_version_id' => $storedObjectVersion->getId(),
            'old_version_version' => $storedObjectVersion->getVersion(),
            'new_version_id' => $newVersion->getVersion(),
        ]);

        return $newVersion;
    }
}
