<?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','order','hide_from_menu','mascot_path','cover_art_path'];

    protected $casts = [
        'order' => 'integer',
        'hide_from_menu' => 'boolean',
    ];

    public function scopeOrdered(EloquentBuilder $query): EloquentBuilder
    {
        return $query->orderBy('order')->orderBy('name')->orderBy('id');
    }

    public function scopeVisibleInToolbar(EloquentBuilder $query): EloquentBuilder
    {
        return $query->where('hide_from_menu', false);
    }

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

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

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

    /**
     * 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 getMascotUrlAttribute(): ?string
    {
        return $this->resolveAssetUrl($this->mascot_path);
    }

    public function getCoverArtUrlAttribute(): ?string
    {
        return $this->resolveAssetUrl($this->cover_art_path);
    }

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

    private function resolveAssetUrl(?string $path): ?string
    {
        $path = trim((string) $path);

        if ($path === '') {
            return null;
        }

        if (str_starts_with($path, 'http://') || str_starts_with($path, 'https://') || str_starts_with($path, '/')) {
            return $path;
        }

        return rtrim((string) config('cdn.files_url', 'https://cdn.skinbase.org'), '/') . '/' . ltrim($path, '/');
    }
}
