<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Compensation;

final class WorkflowCompensationStore
{
    public const CACHE_DIR = 'storage/cache/workflow';
    public const STATE_FILE = 'workflow-compensation-runtime.json';

    public function __construct(
        private readonly string $basePath,
        private readonly WorkflowCompensationSerializer $serializer = new WorkflowCompensationSerializer()
    ) {}

    public function stateFile(): string
    {
        return rtrim($this->basePath, DIRECTORY_SEPARATOR) . '/' . self::CACHE_DIR . '/' . self::STATE_FILE;
    }

    public function save(WorkflowCompensationSnapshot $snapshot): WorkflowCompensationSnapshot
    {
        $file = $this->stateFile();

        if (!is_dir(dirname($file))) {
            mkdir(dirname($file), 0775, true);
        }

        file_put_contents($file, $this->serializer->encode($snapshot));
        return $snapshot;
    }

    public function load(): WorkflowCompensationSnapshot
    {
        $file = $this->stateFile();
        if (!is_file($file)) {
            return new WorkflowCompensationSnapshot();
        }

        return $this->serializer->decode((string) file_get_contents($file));
    }

    public function reset(): void
    {
        $file = $this->stateFile();
        if (is_file($file)) {
            unlink($file);
        }
    }

    public function exists(): bool
    {
        return is_file($this->stateFile());
    }
}
