<?php

declare(strict_types=1);

namespace BotGuard\Models;

use BotGuard\Core\Model;

/**
 * Key/value application settings with typed get/set helpers.
 */
final class Setting extends Model
{
    protected string $table = 'settings';

    public function value(string $key, mixed $default = null): mixed
    {
        $row = $this->firstWhere(['key' => $key]);
        if ($row === null) {
            return $default;
        }

        return match ($row['type']) {
            'int'  => (int) $row['value'],
            'bool' => filter_var($row['value'], FILTER_VALIDATE_BOOLEAN),
            'json' => json_decode((string) $row['value'], true),
            default => $row['value'],
        };
    }

    public function set(string $key, mixed $value, string $type = 'string', string $group = 'general'): void
    {
        $stored = $type === 'json' ? json_encode($value) : (string) $value;
        $existing = $this->firstWhere(['key' => $key]);

        if ($existing === null) {
            $this->create(['key' => $key, 'value' => $stored, 'type' => $type, 'group' => $group]);
        } else {
            $this->updateById((int) $existing['id'], ['value' => $stored, 'type' => $type]);
        }
    }
}
