<?php

namespace App\Models\AbstractModels;

use App\Models\Image;
use App\Services\Image\ImageService;
use Illuminate\Database\Eloquent\Model;


abstract class ImageableModel extends Model
{
    protected ?ImageService $imageService = null;

    public function image()
    {
        return $this->morphOne(Image::class, 'imageable');
    }

    protected function imageService()
    {
        if (\is_null($this->imageService)) {
            $this->imageService = new ImageService;
        }

        return $this->imageService;
    }

    public function appendImageUrl(string $size = '')
    {
        $this->stablishRelationship();
        $this->setHidden(['image']);

        $url = $this->imageService()->getUrl($size);

        $this->setAttribute('imageUrl', $this->image ? $url : null);
    }

    protected function stablishRelationship()
    {
        if (!\is_null($this->image)) {
            $this->imageService()->setImageModel($this->image);
        }

        $this->imageService()->setRelatedModel($this);
    }
}
