<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use HasFactory;
    use HasRoles;
    use Notifiable;

    protected string $guard_name = 'api';

    protected $fillable = [
        'nickname',
        'email',
        'phone',
        'password',
        'force_password_change',
    ];

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

    public function getJWTIdentifier(): mixed
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims(): array
    {
        return [];
    }

    public function serverResources(): BelongsToMany
    {
        return $this->belongsToMany(ServerResource::class, 'user_server_permissions')
            ->withPivot(['can_ssh', 'can_sftp', 'can_rdp'])
            ->withTimestamps();
    }

    public function opsSoftwarePreferences(): HasMany
    {
        return $this->hasMany(UserOpsSoftwarePreference::class);
    }

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

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