<?php

namespace App\Models\Tenants;

use App\Traits\BelongsToTenant;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;

/**
 * 테넌트 설정 모델
 *
 * @property int $id
 * @property int $tenant_id
 * @property string $setting_group
 * @property string $setting_key
 * @property array|null $setting_value
 * @property string|null $description
 * @property int|null $updated_by
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 */
class TenantSetting extends Model
{
    use BelongsToTenant, ModelTrait;

    protected $table = 'tenant_settings';

    protected $fillable = [
        'tenant_id',
        'setting_group',
        'setting_key',
        'setting_value',
        'description',
        'updated_by',
    ];

    protected $casts = [
        'setting_value' => 'array',
    ];

    /**
     * 특정 그룹의 모든 설정 조회
     */
    public function scopeGroup($query, string $group)
    {
        return $query->where('setting_group', $group);
    }

    /**
     * 특정 키의 설정 조회
     */
    public function scopeKey($query, string $key)
    {
        return $query->where('setting_key', $key);
    }

    /**
     * 그룹과 키로 설정 조회
     */
    public static function getValue(int $tenantId, string $group, string $key, $default = null)
    {
        $setting = static::withoutGlobalScope('tenant')
            ->where('tenant_id', $tenantId)
            ->where('setting_group', $group)
            ->where('setting_key', $key)
            ->first();

        return $setting ? $setting->setting_value : $default;
    }

    /**
     * 그룹과 키로 설정 저장/업데이트
     */
    public static function setValue(int $tenantId, string $group, string $key, $value, ?string $description = null, ?int $updatedBy = null): self
    {
        return static::withoutGlobalScope('tenant')->updateOrCreate(
            [
                'tenant_id' => $tenantId,
                'setting_group' => $group,
                'setting_key' => $key,
            ],
            [
                'setting_value' => $value,
                'description' => $description,
                'updated_by' => $updatedBy,
            ]
        );
    }
}
