<?php

namespace App\Support;

use Illuminate\Support\Facades\File;

class IntegrityManifestStore
{
    private const RELATIVE_PATH = 'integrity/core-manifest.json';

    /**
     * @return array<string, mixed>|null
     */
    public static function read(): ?array
    {
        $path = self::path();

        if (! File::exists($path)) {
            return null;
        }

        $decoded = json_decode(File::get($path), true);

        return is_array($decoded) ? $decoded : null;
    }

    /**
     * @param  array<string, mixed>  $manifest
     */
    public static function write(array $manifest): void
    {
        $path = self::path();
        $directory = dirname($path);

        if (! File::isDirectory($directory)) {
            File::makeDirectory($directory, 0755, true);
        }

        File::put($path, json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    }

    public static function version(): ?string
    {
        $manifest = self::read();

        return isset($manifest['version']) ? (string) $manifest['version'] : null;
    }

    public static function path(): string
    {
        return storage_path('app/'.self::RELATIVE_PATH);
    }
}
