<?php

namespace Daylight\Core\Modules\PageBuilder\Concerns;

use Illuminate\Support\Arr;
use Illuminate\Support\Collection;

trait InteractsWithPageBuilder
{
    public function getPageBuilderRules(string $fieldName = 'components', bool $required = true): array
    {
        return [
            $fieldName => $required ? ['required', 'array'] : ['sometimes', 'nullable'],
            $fieldName.'.*.id' => ['sometimes', 'nullable'],
            $fieldName.'.*.type' => ['required', 'string', 'max:255'],
            $fieldName.'.*.data' => ['required', 'array'],
        ];
    }

    public function prepareForValidation(): void
    {
        $this->merge([
            'components' => json_decode($this->input('components'), true),
        ]);
    }

    public function getComponentsFromRequest(string $fieldName = 'components'): Collection
    {
        return collect($this->get($fieldName))
            ->map(function (array $component, $index) {
                return [
                    ...Arr::only($component, ['id', 'type', 'data']),
                    'order' => $index,
                ];
            });
    }
}
