<?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\HasMany;

class Categoria extends Model
{
    use HasFactory;

    protected $fillable = [
        'departamento_id',
        'parent_id',
        'nome',
        'slug',
        'descricao',
        'cor',
        'ordem',
        'ativo',
    ];

    protected $casts = [
        'ativo' => 'boolean',
    ];

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

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

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

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

    public function getNomeCompletoAttribute(): string
    {
        if (! $this->categoriaPai) {
            return $this->nome;
        }

        return "{$this->categoriaPai->nome_completo} / {$this->nome}";
    }
}
