<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\DragDrop;

final class DesignerDragDropHistory
{
    private array $undoStack = [];
    private array $redoStack = [];

    public function record(array $before, array $after, string $operation): void
    {
        $this->undoStack[] = [
            'operation' => $operation,
            'before' => $before,
            'after' => $after,
            'createdAt' => date('c'),
        ];
        $this->redoStack = [];
    }

    public function undo(array $current): array
    {
        $entry = array_pop($this->undoStack);
        if (!$entry) {
            return $current;
        }

        $this->redoStack[] = $entry;
        return (array)$entry['before'];
    }

    public function redo(array $current): array
    {
        $entry = array_pop($this->redoStack);
        if (!$entry) {
            return $current;
        }

        $this->undoStack[] = $entry;
        return (array)$entry['after'];
    }

    public function stats(): array
    {
        return [
            'undo' => count($this->undoStack),
            'redo' => count($this->redoStack),
        ];
    }
}
