<?php

use Illuminate\Database\Migrations\Migration;
use Inside\Host\Bridge\BridgeContent;
use Inside\Host\Bridge\BridgeContentType;

class AddNewsField extends Migration
{
    use \Inside\Host\Migrations\CreateContentTypes;

    public function up(): void
    {
        $this->bootUp(__FILE__);

        $this->migrateContent('regional_office_types', false);
        $this->bridge->contentTypeCreateOrUpdateField('news', 'regional_office_types', [
            'name' => 'regional_office_types',
            'searchable' => false,
            'translatable' => false,
            'search_result_field' => false,
            'required' => false,
            'weight' => 11,
            'title' => [
                'fr' => 'Regional office type',
                'en' => 'Regional office type',
            ],
            'widget' => [
                'type' => BridgeContentType::SELECT_WIDGET,
                'settings' => [],
                'weight' => 11,
                'group' => 'group_publication_workflow',
            ],
            'type' => BridgeContentType::REFERENCE_FIELD,
            'settings' => [
                'target_type' => ['regional_office_types'],
                'cardinality' => 1,
            ],
        ]);
        $this->finishUp();

        $contentMapping = [
            'regional_office_types' => [
                [
                    'title' => 'For Regional Office Only',
                ],
                [
                    'title' => 'Regional Office Article',
                ],
            ],
        ];

        $bridge = new BridgeContent();
        foreach ($contentMapping as $contentType => $contents) {
            foreach ($contents as $content) {
                $data = array_merge($content, [
                    'type' => 'node',
                    'bundle' => $contentType,
                    'langcode' => 'fr',
                ]);

                $this->getConsole()->writeln(sprintf('Creating content %s of content type %s', $data['title'], $contentType));

                $uuid = $bridge->contentInsert($contentType, $data);
                $model = call_user_func(type_to_class('regional_office_types') . '::query')->find($uuid);

                if ($model) {
                    $data['langcode'] = 'en';
                    $data['uuid_host'] = $model->uuid_host;
                    $bridge->contentInsert($contentType, $data);
                }
            }
        }
    }


    public function down(): void
    {
    }
}
