<?php

namespace App\Models\Concerns;

use App\Enums\RoleSlug;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;

trait HasRoles
{
    public function hasRole(RoleSlug $role): bool
    {
        return $this->role?->slug === $role;
    }

    public function hasAnyRole(RoleSlug ...$roles): bool
    {
        return $this->role?->slug instanceof RoleSlug && in_array($this->role->slug, $roles, true);
    }

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

    public function isManager(): bool
    {
        return $this->hasRole(RoleSlug::Manager);
    }

    #[Scope]
    protected function withRole(Builder $query, RoleSlug $role): void
    {
        $query->whereRelation('role', 'slug', $role);
    }

    #[Scope]
    protected function withAnyRole(Builder $query, RoleSlug ...$roles): void
    {
        $query->whereHas(
            'role',
            fn (Builder $roleQuery) => $roleQuery->whereIn('slug', $roles),
        );
    }
}
