<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Verification;

final class WorkflowRuntimeStore
{
    public const REPORT_FILE = 'storage/reports/r0100/r0100-workflow-runtime-report.json';
    public const LOCK_FILE = 'storage/reports/r0100/r0100-workflow-runtime-lock.json';

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

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

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

    public function saveReport(WorkflowRuntimeReport $report): WorkflowRuntimeReport
    {
        $file = $this->reportFile();
        if (!is_dir(dirname($file))) {
            mkdir(dirname($file), 0775, true);
        }
        file_put_contents($file, $this->serializer->encode($report->toArray()));
        return $report;
    }

    public function saveLock(WorkflowRuntimeLock $lock): WorkflowRuntimeLock
    {
        $file = $this->lockFile();
        if (!is_dir(dirname($file))) {
            mkdir(dirname($file), 0775, true);
        }
        file_put_contents($file, $this->serializer->encode($lock->toArray()));
        return $lock;
    }

    public function loadReport(): ?WorkflowRuntimeReport
    {
        $file = $this->reportFile();
        if (!is_file($file)) {
            return null;
        }
        return WorkflowRuntimeReport::fromArray($this->serializer->decode((string) file_get_contents($file)));
    }

    public function loadLock(): ?WorkflowRuntimeLock
    {
        $file = $this->lockFile();
        if (!is_file($file)) {
            return null;
        }
        return WorkflowRuntimeLock::fromArray($this->serializer->decode((string) file_get_contents($file)));
    }

    public function reportExists(): bool { return is_file($this->reportFile()); }
    public function lockExists(): bool { return is_file($this->lockFile()); }
}
