<?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\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Cache;

#[Fillable(['branch_id', 'name', 'email', 'phone', 'role', 'status', 'last_login_at', 'last_login_ip', 'password'])]
#[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',
            'last_login_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    public function branch()
    {
        return $this->belongsTo(Branch::class);
    }

    public function isOwner(): bool
    {
        return $this->role === 'owner';
    }

    public function hasRole(string ...$roles): bool
    {
        return in_array($this->role, $roles, true);
    }

    public function canAccessBranch(int $branchId): bool
    {
        return $this->isOwner() || (int) $this->branch_id === $branchId;
    }

    public function canPermission(string $permission): bool
    {
        if ($this->isOwner()) {
            return true;
        }

        $allowed = Cache::remember("role-permissions:{$this->role}", 60, function (): array {
            return RolePermission::query()
                ->where('role', $this->role)
                ->where('allowed', true)
                ->pluck('permission')
                ->all();
        });

        return in_array($permission, $allowed, true);
    }
}
