<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;

class UserRole extends Authenticatable
{
    use HasFactory, HasApiTokens;

    protected $primaryKey = 'email';
    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'email',
        'role',
        'is_active',
        'last_login_at',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'last_login_at' => 'datetime',
    ];

    /**
     * Get the password for the user (required by Authenticatable)
     * UserRole doesn't use passwords, return empty string
     */
    public function getAuthPassword()
    {
        return '';
    }

    /**
     * Get visits created by this user as host
     */
    public function visits()
    {
        return $this->hasMany(Visit::class, 'host_email', 'email');
    }

    /**
     * Get visits reviewed by this user
     */
    public function reviewedVisits()
    {
        return $this->hasMany(Visit::class, 'reviewed_by_email', 'email');
    }

    /**
     * Get status history changes made by this user
     */
    public function statusChanges()
    {
        return $this->hasMany(VisitStatusHistory::class, 'changed_by_email', 'email');
    }

    /**
     * Check if user has a specific role
     * @param string|array $roles
     * @return bool
     */
    public function hasRole($roles): bool
    {
        $roles = is_array($roles) ? $roles : [$roles];
        return in_array($this->role, $roles);
    }

    /**
     * Scope to get only active users
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }
}
