<?php

declare(strict_types=1);

namespace FatBottom\Core;

final class Config
{
    private array $values;

    public function __construct(
        private readonly array $defaults,
        private readonly string $path
    ) {
        $saved = [];
        if (is_file($path)) {
            $decoded = json_decode((string) file_get_contents($path), true);
            if (is_array($decoded)) {
                $saved = $decoded;
            }
        }

        $this->values = array_replace_recursive($defaults, $saved);
    }

    public function all(): array
    {
        return $this->values;
    }

    public function get(string $key, mixed $default = null): mixed
    {
        $value = $this->values;
        foreach (explode('.', $key) as $segment) {
            if (!is_array($value) || !array_key_exists($segment, $value)) {
                return $default;
            }
            $value = $value[$segment];
        }

        return $value;
    }

    public function set(string $key, mixed $newValue): void
    {
        $segments = explode('.', $key);
        $value = &$this->values;
        foreach ($segments as $segment) {
            if (!isset($value[$segment]) || !is_array($value[$segment])) {
                $value[$segment] = [];
            }
            $value = &$value[$segment];
        }
        $value = $newValue;
    }

    public function save(): void
    {
        $directory = dirname($this->path);
        if (!is_dir($directory)) {
            mkdir($directory, 0775, true);
        }

        file_put_contents(
            $this->path,
            json_encode($this->values, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL,
            LOCK_EX
        );
        @chmod($this->path, 0600);
    }

    public function reset(): void
    {
        $this->values = $this->defaults;
        $this->save();
    }
}
