<?php

namespace App\Models;

use App\ImportConditionRepository;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use OwenIt\Auditing\Contracts\Auditable;

class ImportConditionRule extends Model implements Auditable
{
    use \OwenIt\Auditing\Auditable;

    protected $fillable = [
        'import_condition_id',
        'field',
        'condition',
        'value',
        'data',
    ];

    protected $casts = [
        'active' => 'boolean',
        'data' => 'array',
    ];

    protected $appends = [
        'field_name',
        'condition_name',
        'value_name',
    ];

    public function condition(): BelongsTo
    {
        return $this->belongsTo(ImportCondition::class);
    }

    public function getFieldNameAttribute(): string
    {
        return __('vehicles.' . $this->field);
    }

    public function getConditionNameAttribute(): string
    {
        return __('labels.conditions.' . $this->condition);
    }

    public function getValueNameAttribute()
    {
        $repository = new ImportConditionRepository();

        // Check if value is JSON-encoded array (for in/not_in conditions)
        $decoded = json_decode($this->value, true);
        if (is_array($decoded)) {
            return collect($decoded)
                ->map(fn ($id) => $repository->getValue($this->field, $id))
                ->implode(', ');
        }

        return $repository->getValue($this->field, $this->value);
    }
}
