<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Enums\UserRole;
use App\Policies\UserPolicy;
use Database\Factories\UserFactory;
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Attributes\UsePolicy;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

#[UsePolicy(UserPolicy::class)]
#[Fillable(['name', 'email', 'password', 'role', 'is_active'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable implements FilamentUser
{
    /** @use HasFactory<UserFactory> */
    use HasFactory, Notifiable;

    public function canAccessPanel(Panel $panel): bool
    {
        return $panel->getId() === 'admin' && $this->is_active;
    }

    public function isAdmin(): bool
    {
        return $this->role === UserRole::Admin;
    }

    public function isCollaborator(): bool
    {
        return $this->role === UserRole::Collaborator;
    }

    public function canAdministerUsers(): bool
    {
        return $this->is_active && $this->isAdmin();
    }

    public function isLastActiveAdmin(): bool
    {
        if (! $this->exists || ! $this->is_active || ! $this->isAdmin()) {
            return false;
        }

        return ! self::query()
            ->whereKeyNot($this->getKey())
            ->where('role', UserRole::Admin->value)
            ->where('is_active', true)
            ->exists();
    }

    public function canBeDeactivatedBy(User $actor): bool
    {
        return $actor->canAdministerUsers()
            && ! $this->is($actor)
            && ! $this->isLastActiveAdmin();
    }

    public function canBeDeletedBy(User $actor): bool
    {
        return $actor->canAdministerUsers()
            && ! $this->is($actor)
            && ! $this->isLastActiveAdmin();
    }

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