<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ServerResource extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'display_name',
        'parent_id',
        'internal_ip',
        'asset_id',
        'account_id',
        'protocols',
        'description',
        'allow_copy_temp_password',
        'is_active',
    ];

    public function parent(): BelongsTo
    {
        return $this->belongsTo(self::class, 'parent_id');
    }

    public function children(): HasMany
    {
        return $this->hasMany(self::class, 'parent_id');
    }

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

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

    protected function casts(): array
    {
        return [
            'protocols' => 'array',
            'allow_copy_temp_password' => 'boolean',
            'is_active' => 'boolean',
        ];
    }
}
