<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;use App\Models\Concerns\BelongsToCompany;


class Department extends Model
{
    use LogsActivity, BelongsToCompany;

    protected $fillable = [
        'name', 'description', 'color', 'parent_id', 'manager_id', 'active', 'order'
    ];

    protected function casts(): array {
        return ['active' => 'boolean'];
    }

    // Relaciones
    public function parent(): BelongsTo {
        return $this->belongsTo(Department::class, 'parent_id');
    }
    public function children(): HasMany {
        return $this->hasMany(Department::class, 'parent_id');
    }
    public function manager(): BelongsTo {
        return $this->belongsTo(User::class, 'manager_id');
    }
    public function users(): HasMany {
        return $this->hasMany(User::class);
    }
    public function schedules(): HasMany {
        return $this->hasMany(Schedule::class);
    }

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

    // Activity Log
    public function getActivitylogOptions(): LogOptions {
        return LogOptions::defaults()
            ->logOnly(['name', 'active', 'manager_id'])
            ->logOnlyDirty()
            ->setDescriptionForEvent(fn(string $e) => match($e) {
                'created' => "Departamento {$this->name} creado",
                'updated' => "Departamento {$this->name} actualizado",
                'deleted' => "Departamento {$this->name} eliminado",
                default   => "Departamento {$this->name}: {$e}",
            });
    }
}
