<?php

namespace App\Models;

use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;

/**
 * @property int $id
 * @property int $registrar_id
 * @property string $setting
 * @property string|null $value
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 *
 * @method static \Illuminate\Database\Eloquent\Builder<static>|RegistrarSetting newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|RegistrarSetting newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|RegistrarSetting query()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|RegistrarSetting whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|RegistrarSetting whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|RegistrarSetting whereRegistrarId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|RegistrarSetting whereSetting($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|RegistrarSetting whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|RegistrarSetting whereValue($value)
 *
 * @property-read \App\Models\Registrar|null $registrar
 *
 * @mixin \Eloquent
 */
class RegistrarSetting extends Model
{
    use HasFactory;

    protected $fillable = [
        'registrar_id',
        'setting',
        'value',
    ];

    /**
     * PRC-171: registrar settings (API key, password, secret) encrypted
     * at-rest. The table holds ~10 rows per registrar so the
     * encrypt-everything-unconditionally approach is acceptable — avoids
     * a circular Registrar->module->configFields lookup inside the
     * accessor. Accessor falls back to raw on decrypt failure so legacy
     * plaintext rows survive the migration window.
     */
    public function getValueAttribute(?string $value): ?string
    {
        if ($value === null || $value === '') {
            return $value;
        }
        try {
            return Crypt::decryptString($value);
        } catch (DecryptException $e) {
            return $value;
        }
    }

    public function setValueAttribute(?string $value): void
    {
        if ($value === null || $value === '') {
            $this->attributes['value'] = $value;
            return;
        }
        $this->attributes['value'] = Crypt::encryptString($value);
    }

    /**
     * Bu ayarın ait olduğu registrar'ı getirir
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function registrar()
    {
        return $this->belongsTo(Registrar::class);
    }
}
