<?php

namespace Modules\Category\Models;

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

class Category extends Model
{
    protected $fillable = [
        'name',
        'slug',
        'icon',
        'description',
        'sort_order',
        'is_active',
    ];

    protected $appends = ['image_url'];

    public function products(): HasMany
    {
        return $this->hasMany(\Modules\Product\Models\Product::class);
    }

    public function media(): MorphMany
    {
        return $this->morphMany(\Modules\Media\Models\Media::class, 'mediable');
    }

    public function getImageUrlAttribute(): ?string
    {
        $media = $this->relationLoaded('media')
            ? $this->media
            : $this->media()->latest()->take(1)->get();

        if ($media->isNotEmpty()) {
            $path = $media->first()->path;
            if ($path && !str_starts_with($path, 'http')) {
                return url('storage/' . $path);
            }
            return $path;
        }

        return $this->getRawOriginal('image_url');
    }
}
