<?php

namespace App\Models\Definition;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class DefinitionAttribute extends Model
{
    use HasFactory;

    protected $fillable = [
        'definition_type_id',
        'name',
        'display_name',
        'field_type',
        'description',
        'options',
        'validation_rules',
        'default_value',
        'is_required',
        'is_searchable',
        'is_filterable',
        'is_system',
        'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'options' => 'array',
            'validation_rules' => 'array',
            'is_required' => 'boolean',
            'is_searchable' => 'boolean',
            'is_filterable' => 'boolean',
            'is_system' => 'boolean',
        ];
    }

    public function definitionType()
    {
        return $this->belongsTo(DefinitionType::class);
    }

    public function values()
    {
        return $this->hasMany(DefinitionValue::class);
    }

    public function getInputTypeAttribute()
    {
        $typeMapping = [
            'text' => 'text',
            'textarea' => 'textarea',
            'number' => 'number',
            'date' => 'date',
            'boolean' => 'checkbox',
            'select' => 'select',
            'file' => 'file',
        ];

        return $typeMapping[$this->field_type] ?? 'text';
    }

    public function getValidationRulesString()
    {
        $rules = [];

        if ($this->is_required) {
            $rules[] = 'required';
        }

        if ($this->validation_rules) {
            foreach ($this->validation_rules as $rule => $value) {
                if ($value) {
                    $rules[] = is_numeric($rule) ? $value : "$rule:$value";
                }
            }
        }

        return implode('|', $rules);
    }

    public function scopeRequired($query)
    {
        return $query->where('is_required', true);
    }

    public function scopeSearchable($query)
    {
        return $query->where('is_searchable', true);
    }

    public function scopeFilterable($query)
    {
        return $query->where('is_filterable', true);
    }

    public function scopeSystem($query)
    {
        return $query->where('is_system', true);
    }

    public function scopeCustom($query)
    {
        return $query->where('is_system', false);
    }

    public function scopeByType($query, $typeId)
    {
        return $query->where('definition_type_id', $typeId);
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order');
    }
}
