<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class TicketCategory extends Model
{
    use LogsActivity;

    protected $fillable = ['name','description','icon','color','parent_id','active','order'];
    protected function casts(): array { return ['active' => 'boolean']; }

    public function parent(): BelongsTo { return $this->belongsTo(TicketCategory::class, 'parent_id'); }
    public function children(): HasMany { return $this->hasMany(TicketCategory::class, 'parent_id'); }
    public function tickets(): HasMany { return $this->hasMany(Ticket::class, 'category_id'); }

    public function scopeActive($q) { return $q->where('active', true); }
    public function scopeRoots($q)  { return $q->whereNull('parent_id'); }

    public function getActivitylogOptions(): LogOptions {
        return LogOptions::defaults()->logOnly(['name','active'])->logOnlyDirty()
            ->setDescriptionForEvent(fn($e) => "Categoría {$this->name}: {$e}");
    }
}
