<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Verification;

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

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

    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(WorkflowFullRuntimeReport $report): WorkflowFullRuntimeReport
    {
        $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(WorkflowFullRuntimeLock $lock): WorkflowFullRuntimeLock
    {
        $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(): ?WorkflowFullRuntimeReport
    {
        $file = $this->reportFile();
        if (!is_file($file)) {
            return null;
        }

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

    public function loadLock(): ?WorkflowFullRuntimeLock
    {
        $file = $this->lockFile();
        if (!is_file($file)) {
            return null;
        }

        return WorkflowFullRuntimeLock::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()); }
}
