<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $fillable = ['username', 'email', 'password', 'role_id', 'status', 'verified', 'display_name', 'uuid'];

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

    protected function casts(): array
    {
        return ['password' => 'hashed', 'verified' => 'boolean'];
    }

    public function profile(): HasOne
    {
        return $this->hasOne(Profile::class);
    }

    public function role(): BelongsTo
    {
        return $this->belongsTo(Role::class);
    }

    public function professional(): HasOne
    {
        return $this->hasOne(Professional::class);
    }

    public function isAdmin(): bool
    {
        $allowed = collect(explode(',', (string) config('admin.emails')))->map(fn ($email) => strtolower(trim($email)));

        return in_array(strtolower((string) $this->role?->name), ['admin', 'administrator', 'system admin'], true) || $allowed->contains(strtolower($this->email));
    }

    public function isSystemAdmin(): bool
    {
        return strtolower((string) $this->role?->name) === 'system admin';
    }
}
