<?php

declare(strict_types=1);

namespace ImovelZapAi\SuperAdmin\Application\Services;

use ImovelZapAi\SuperAdmin\Infrastructure\Persistence\Eloquent\PlatformSettingModel;

final class PlatformSettingsStore
{
    public function get(string $key, mixed $default = null): mixed
    {
        $row = PlatformSettingModel::query()->where('key', $key)->first();
        if ($row === null) {
            return $default;
        }

        $value = $row->value;

        return is_array($value) && array_key_exists('v', $value) ? $value['v'] : ($value ?? $default);
    }

    public function set(string $key, mixed $value): PlatformSettingModel
    {
        return PlatformSettingModel::query()->updateOrCreate(
            ['key' => $key],
            ['value' => ['v' => $value]],
        );
    }

    public function maintenanceMode(): bool
    {
        return (bool) $this->get('maintenance_mode', false);
    }

    /**
     * @return list<string>
     */
    public function ipAllowlist(): array
    {
        $raw = $this->get('ip_allowlist', []);
        if (! is_array($raw)) {
            return [];
        }

        return array_values(array_filter(array_map('strval', $raw)));
    }

    /**
     * @return array<string, bool>
     */
    public function featureFlags(): array
    {
        $raw = $this->get('feature_flags', []);
        if (! is_array($raw)) {
            return [];
        }

        $flags = [];
        foreach ($raw as $k => $v) {
            $flags[(string) $k] = (bool) $v;
        }

        return $flags;
    }
}
