<?php
declare(strict_types=1);

function store_path(string $name): string
{
    return DATA_PATH . '/' . $name . '.json';
}

function store_read(string $name): array
{
    $path = store_path($name);
    if (!is_file($path)) {
        return [];
    }

    $raw = file_get_contents($path);
    if ($raw === false || $raw === '') {
        return [];
    }

    $data = json_decode($raw, true);
    return is_array($data) ? $data : [];
}

function store_write(string $name, array $data): bool
{
    $path = store_path($name);
    $dir = dirname($path);
    if (!is_dir($dir)) {
        mkdir($dir, 0775, true);
    }

    $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    if ($json === false) {
        return false;
    }

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

function store_find(string $name, string $id): ?array
{
    foreach (store_read($name) as $item) {
        if (($item['id'] ?? '') === $id) {
            return $item;
        }
    }
    return null;
}

function store_upsert(string $name, array $item, string $idKey = 'id'): bool
{
    $items = store_read($name);
    $found = false;

    foreach ($items as $i => $row) {
        if (($row[$idKey] ?? null) === ($item[$idKey] ?? null)) {
            $items[$i] = $item;
            $found = true;
            break;
        }
    }

    if (!$found) {
        $items[] = $item;
    }

    return store_write($name, $items);
}

function store_delete(string $name, string $id, string $idKey = 'id'): bool
{
    $items = array_values(array_filter(
        store_read($name),
        static fn(array $row): bool => ($row[$idKey] ?? null) !== $id
    ));

    return store_write($name, $items);
}

function new_id(string $prefix = ''): string
{
    return $prefix . bin2hex(random_bytes(8));
}
