<?php

declare(strict_types=1);

namespace PpPhp\Core;

/**
 * Lightweight per‑module state storage.
 * Each module reads/writes its own JSON file inside config/.
 *
 * Usage:
 *   $data = ModuleState::load('my-project', 'misc');
 *   ModuleState::save('my-project', 'misc', $data);
 */
class ModuleState
{
    /**
     * Load the state for a module.
     */
    public static function load(string $slug, string $module): array
    {
        $file = self::path($slug, $module);
        if (file_exists($file)) {
            $data = json_decode(file_get_contents($file), true);
            if (is_array($data) && !array_is_list($data)) {
                return $data;
            }
        }
        return [];
    }

    /**
     * Save the state for a module (complete overwrite, not merge).
     */
    public static function save(string $slug, string $module, array $data): void
    {
        $file = self::path($slug, $module);
        $dir = dirname($file);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT));
    }

    private static function path(string $slug, string $module): string
    {
        // Resolve to the project's real owner so an administrator editing another
        // user's project reads/writes the correct config folder.
        return ProjectLocator::dir($slug) . "/config/{$module}.json";
    }
}
