<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Traits\Auditable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Schema;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable, Auditable;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'role',
        'role_id',
    ];

    protected static function booted(): void
    {
        static::saving(function (User $user): void {
            if (! Schema::hasTable('roles')) {
                return;
            }

            if (filled($user->role_id)) {
                $role = $user->relationLoaded('roleModel') ? $user->roleModel : $user->roleModel()->first();

                if ($role) {
                    $user->role = $role->slug;
                }

                return;
            }

            if (filled($user->role)) {
                $roleId = Role::query()->where('slug', $user->role)->value('id');

                if ($roleId) {
                    $user->role_id = $roleId;
                }
            }
        });
    }

    public function roleModel(): BelongsTo
    {
        return $this->belongsTo(Role::class, 'role_id');
    }

    public function roleSlug(): ?string
    {
        return $this->roleModel?->slug ?? $this->role;
    }

    public function accessLevel(): string
    {
        if ($this->roleModel?->access_level) {
            return $this->roleModel->access_level;
        }

        return in_array($this->role, ['admin', 'editor'], true) ? $this->role : 'user';
    }

    public function isAdmin(): bool
    {
        return $this->hasRole('admin');
    }

    public function isEditor(): bool
    {
        return $this->hasRole('editor');
    }

    public function hasRole(string $role): bool
    {
        return $this->roleSlug() === $role;
    }

    public function hasAnyRole(array $roles): bool
    {
        foreach ($roles as $role) {
            if ($this->hasRole($role)) {
                return true;
            }
        }

        return false;
    }

    public function permissions(): array
    {
        if ($this->roleModel) {
            return $this->roleModel->permissionKeys();
        }

        return Role::defaultPermissionsForSlug($this->roleSlug());
    }

    public function hasPermission(string $permission): bool
    {
        return in_array($permission, $this->permissions(), true);
    }

    public function hasAnyPermission(array $permissions): bool
    {
        foreach ($permissions as $permission) {
            if ($this->hasPermission($permission)) {
                return true;
            }
        }

        return false;
    }

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

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