<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class DocumentoCartella extends Model
{
    protected $table = 'documenti_cartelle';

    protected $fillable = ['parent_id', 'nome'];

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

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

    public function documenti(): HasMany
    {
        return $this->hasMany(Documento::class, 'cartella_id');
    }

    public function ancestors(): array
    {
        $ancestors = [];
        $current = $this;
        while ($current->parent) {
            array_unshift($ancestors, $current->parent);
            $current = $current->parent;
        }
        return $ancestors;
    }

    public function fullPath(): string
    {
        $parts = collect($this->ancestors())->push($this)->pluck('nome')->toArray();
        return '/' . implode('/', $parts);
    }
}
