<?php

namespace App\Models;

use App\Enums\Status;
use App\Traits\HasTree;
use Illuminate\Database\Eloquent\Builder;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ContentCategory extends BaseModel
{
    use HasTree;

    protected $table = 'content_categories';

    public const CREATED_AT = 'create_time';

    public const UPDATED_AT = 'update_time';

    protected $fillable = [
        'parent_id',
        'model_id',
        'name',
        'icon',
        'image',
        'description',
        'sort',
        'status',
    ];

    protected $casts = [
        'status' => Status::class,
    ];

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

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

    public function model(): BelongsTo
    {
        return $this->belongsTo(ContentModel::class, 'model_id');
    }

    public function contents(): HasMany
    {
        return $this->hasMany(Content::class, 'category_id');
    }

    public function scopeEnabled(Builder $query): Builder
    {
        return $query->where('status', Status::ENABLED);
    }

    public function getIsLeafAttribute(): bool
    {
        return ! $this->children()->exists();
    }
}
