<?php

namespace ZenoChatbot\Services\Indexing\Store;

class IndexFileStore
{
    /** @return array<int,array<string,mixed>> */
    public static function readJsonArray(string $filePath): array
    {
        if (!file_exists($filePath)) {
            return [];
        }

        $content = file_get_contents($filePath);
        if ($content === false || $content === '') {
            return [];
        }

        $decoded = json_decode($content, true);
        return is_array($decoded) ? $decoded : [];
    }

    /** @param array<mixed> $payload */
    public static function writeJson(string $filePath, array $payload): bool
    {
        $json = json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        if ($json === false) {
            return false;
        }

        return file_put_contents($filePath, $json, LOCK_EX) !== false;
    }
}
