<?php

namespace App\Models;

/**
 * Raw key/value access to the tenant_settings table (see Phase 1's
 * CreateTenantSettingsTable). Application code should use App\Libraries\
 * Settings instead of this model directly — it adds encryption for
 * sensitive values (API keys/secrets) and a typed get/set API. This model
 * exists mainly so Settings has something to persist through.
 */
class TenantSettingModel extends TenantModel
{
    protected $table         = 'tenant_settings';
    protected $primaryKey    = 'id';
    protected $returnType    = 'object';
    protected $useTimestamps = true;

    protected $allowedFields = ['key', 'value'];

    public function getValue(string $key): ?string
    {
        $row = $this->where('key', $key)->first();

        return $row->value ?? null;
    }

    public function setValue(string $key, ?string $value): void
    {
        $existing = $this->where('key', $key)->first();

        if ($existing === null) {
            $this->insert(['key' => $key, 'value' => $value]);
        } else {
            $this->update($existing->id, ['value' => $value]);
        }
    }
}
