<?php

namespace Daylight\Core\Modules\PageBuilder\Concerns;

use Daylight\Core\Modules\PageBuilder\Models\Component;
use Daylight\Core\Modules\PageBuilder\Transformers\ComponentDataTransformer;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Relations\MorphMany;

trait InteractsWithComponents
{
    public function components(): MorphMany
    {
        return $this
            ->morphMany(Component::class, 'buildable')
            ->orderBy('order');
    }

    public function formattedComponentData(): Attribute
    {
        $this->loadMissing('components');

        return Attribute::make(
            get: fn () => ComponentDataTransformer::for($this->components)
        );
    }
}
