<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

#[Fillable(['name', 'apellido', 'cedula', 'telefono', 'email', 'password', 'role_id', 'active'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable
{
    /** @use HasFactory<UserFactory> */
    use HasFactory, Notifiable;

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'active' => 'boolean',
        ];
    }

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

    /**
     * Administrador pleno: bypassa todos los chequeos de permiso granular.
     */
    public function esAdmin(): bool
    {
        return (bool) $this->role?->es_admin;
    }

    /**
     * True si el rol de este usuario tiene el permiso dado (los administradores
     * siempre pasan, sin importar la matriz de permisos togglable).
     */
    public function puede(string $clave): bool
    {
        if ($this->esAdmin()) {
            return true;
        }

        return $this->role?->permisos->contains('clave', $clave) ?? false;
    }

    /**
     * True si este usuario es el único administrador activo del sistema
     * (perderlo dejaría el panel sin nadie con permisos totales).
     */
    public function esUltimoAdminActivo(): bool
    {
        if (! $this->esAdmin() || ! $this->active) {
            return false;
        }

        return ! static::query()
            ->whereHas('role', fn ($q) => $q->where('es_admin', true))
            ->where('active', true)
            ->where('id', '!=', $this->id)
            ->exists();
    }
}
