<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
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', 'is_available',
        'phone', 'extension', 'position', 'location', 'avatar', 'department_id'
    ];

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

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

    // Relaciones
    public function department(): BelongsTo {
        return $this->belongsTo(Department::class);
    }
    public function agentGroups(): BelongsToMany {
        return $this->belongsToMany(AgentGroup::class, 'agent_group_user');
    }

    // Scopes
    public function scopeActive($query) {
        return $query->where('is_active', true);
    }
    public function assignedTickets(): \Illuminate\Database\Eloquent\Relations\HasMany {
        return $this->hasMany(\App\Models\Ticket::class, "assignee_id");
    }

    public function scopeAgents($query) {
        return $query->whereHas('roles', fn($q) => $q->whereIn('name', ['agente', 'jefe_soporte']));
    }
    public function scopeAvailable($query) {
        return $query->where('is_available', true)->where('is_active', true);
    }

    // Helpers
    public function getAvatarUrlAttribute(): string {
        return $this->avatar
            ? asset('storage/' . $this->avatar)
            : 'https://ui-avatars.com/api/?name=' . urlencode($this->name) . '&color=2E86AB&background=E8F4F8';
    }

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