<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;

use App\Models\Artwork;

class ContentType extends Model
{
    protected $fillable = ['name','slug','description'];

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

    public function rootCategories(): HasMany
    {
        return $this->categories()->whereNull('parent_id');
    }

    /**
     * Return an Eloquent builder for Artworks that belong to this content type.
     * This traverses the pivot `artwork_category` via the `categories` relation.
     * Note: not a direct Eloquent relation (uses whereHas) so it can be queried/eager-loaded manually.
     */
    public function artworks(): EloquentBuilder
    {
        return Artwork::whereHas('categories', function ($q) {
            $q->where('content_type_id', $this->id);
        });
    }

    public function getRouteKeyName(): string
    {
        return 'slug';
    }
}
