<?php

declare(strict_types=1);

namespace App\Framework\Filesystem\Traits;

use App\Framework\Filesystem\Exceptions\FileWriteException;

/**
 * Trait für Atomic Storage-Operationen
 *
 * Implementiert atomare Schreiboperationen durch temporäre Dateien
 * und rename()-Operation für Data Consistency.
 */
trait AtomicStorageTrait
{
    public function putAtomic(string $path, string $content): void
    {
        $generator = new \App\Framework\Ulid\UlidGenerator();
        $tempPath = $path . '.tmp.' . $generator->generate();
        $this->put($tempPath, $content);

        $resolvedPath = $this->resolvePath($path);
        $resolvedTempPath = $this->resolvePath($tempPath);

        if (! @rename($resolvedTempPath, $resolvedPath)) {
            @unlink($resolvedTempPath);

            throw new FileWriteException($path);
        }
    }

    public function updateAtomic(string $path, callable $updateCallback): void
    {
        $originalContent = $this->exists($path) ? $this->get($path) : '';
        $newContent = $updateCallback($originalContent);
        $this->putAtomic($path, $newContent);
    }

    public function updateJsonAtomic(string $path, callable $updateCallback): void
    {
        $originalData = $this->exists($path) ? json_decode($this->get($path), true) ?? [] : [];
        $newData = $updateCallback($originalData);
        $this->putAtomic($path, json_encode($newData, JSON_PRETTY_PRINT));
    }
}
