<?php

namespace Daylight\Core\Modules\PageBuilder\Services;

use Daylight\Core\Modules\PageBuilder\Contracts\HasComponents;
use Daylight\Core\Modules\PageBuilder\Registries\ComponentRegistry;
use Illuminate\Support\Collection;

class ComponentSyncService
{
    public function __construct(
        private ComponentRegistry $registry
    ) {
        //
    }

    public function sync(Collection $components, HasComponents $owner): void
    {
        $preserved = [];

        foreach ($components as $index => $componentData) {
            $definition = $this->registry->getDefinition($componentData['type']);
            $handler = new ComponentHandler($componentData, $definition, $owner, $index);

            $preserved[] = $handler->save();
        }

        $owner->components()->whereNotIn('id', $preserved)->delete();
    }
}
