<?php

namespace Daylight\Core\Modules\PageBuilder\Models;

use Daylight\Core\Modules\MediaLibrary\Contracts\HasMedia;
use Daylight\Core\Modules\MediaLibrary\Models\Concerns\InteractsWithMedia;
use Daylight\Core\Modules\MenuBuilder\Menu;
use Daylight\Core\Modules\PageBuilder\Models\Pivot\Relatable;
use Daylight\Core\Modules\PageBuilder\Registries\ComponentRegistry;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\MorphToMany;

class Component extends Model implements HasMedia
{
    use InteractsWithMedia;

    protected $guarded = [];

    protected $casts = [
        'data' => 'json',
    ];

    public function buildable(): MorphTo
    {
        return $this->morphTo();
    }

    public function definition(): Attribute
    {
        return Attribute::make(
            get: fn () => ComponentRegistry::getDefinition($this->type),
        );
    }

    public function relatables(): HasMany
    {
        return $this->hasMany(Relatable::class)->with('relatable');
    }

    public function menus(): MorphToMany
    {
        return $this->morphedByMany(Menu::class, 'relatable');
    }

    public function products(): MorphToMany
    {
        return $this->morphedByMany(daylightModel('product'), 'relatable');
    }
}
