<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class User extends Authenticatable
{
    use HasFactory, Notifiable, HasRoles, LogsActivity;

    protected $fillable = [
        'name',
        'email',
        'password',
        'is_active',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'is_active' => 'boolean',
        ];
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['name', 'email', 'is_active'])
            ->logOnlyDirty()
            ->setDescriptionForEvent(fn(string $eventName) => match($eventName) {
                'created' => "Usuario {$this->name} creado",
                'updated' => "Usuario {$this->name} actualizado",
                'deleted' => "Usuario {$this->name} eliminado",
                default => "Usuario {$this->name}: {$eventName}",
            });
    }

    /**
     * Asignaciones de procesos a este usuario.
     */
    public function asignaciones(): HasMany
    {
        return $this->hasMany(\App\Models\Asignacion::class);
    }

    /**
     * Asignaciones activas.
     */
    public function asignacionesActivas(): HasMany
    {
        return $this->hasMany(\App\Models\Asignacion::class)->where('activo', true);
    }
}
