<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Manifest;

final class ManifestCache
{
    public function __construct(
        private readonly string $cacheFile
    ) {}

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

    public function load(): ?ManifestCollection
    {
        if (!$this->exists()) {
            return null;
        }

        $data = json_decode((string) file_get_contents($this->cacheFile), true);

        if (!is_array($data) || !is_array($data['manifests'] ?? null)) {
            return null;
        }

        $collection = new ManifestCollection();

        foreach ($data['manifests'] as $record) {
            if (is_array($record)) {
                $collection->add(ManifestFactory::fromArray($record, (string)($record['source'] ?? '')));
            }
        }

        return $collection;
    }

    public function save(ManifestCollection $collection): void
    {
        $dir = dirname($this->cacheFile);

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

        file_put_contents($this->cacheFile, json_encode([
            'generatedAt' => date('c'),
            'count' => $collection->count(),
            'types' => $collection->types(),
            'manifests' => $collection->toArray(),
        ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    }

    public function clear(): void
    {
        if (is_file($this->cacheFile)) {
            unlink($this->cacheFile);
        }
    }
}
