<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
use Inside\Content\Facades\Schema;
use Inside\Content\Models\Field;
use Inside\Database\Migrations\HasConsole;
use Inside\Host\Bridge\BridgeContent;
use Inside\Host\Bridge\BridgeContentType;

class RemoveBclhLinksFromDrupal extends Migration
{
    use HasConsole;

    public function up(): void
    {
        $fields = Field::query()->where('type', 'link')->orderBy('name')->get();
        $tmp = [];
        $bridgeContentType = new BridgeContentType();
        $bridge = new BridgeContent();
        $this->write('starting to fetch all drupal links ...');
        foreach ($fields as $field) {
            $model = $field->model;
            if (! $model) {
                continue;
            }
            $class = $model->class;
            if (Inside\Support\Str::contains($model->options['name'], '_menus')) {
                // we don't touch drupal content types
                continue;
            }

            if (Schema::isSectionType(class_to_type($model->class))) {
                continue;
            }

            $entityType = $model->options['name'] === 'users' ? 'user' : 'node';

            $tmp[$model->options['name']] = [
                'field_name' => $field->name,
                'required' => $field->options['required'],
                'weight' => $field->options['weight'],
                'translatable' => $field->options['translatable'],
                'title' => $field->options['title'],
                'entity_type' => $entityType,
                'contents' => [],
            ];

            $query = call_user_func($class.'::query');
            $contents = $query->where($field->name, '!=', null)->get();
            foreach ($contents as $content) {
                $tmp[$model->options['name']]['contents'][] = [
                    'uuid' => $content->uuid,
                    'link' => $content->{$field->name},
                ];
            }
        }
        $this->writeln(' <fg=green>✔</fg=green>');
        $this->write('deleting all drupal fields (except drupal menus) ...');
        // need to do two loops because we can't create a new field when old ones still exists with the same name
        foreach ($tmp as $key => $item) {
            $bridgeContentType->contentTypeDeleteField($item['entity_type'], $key, $item['field_name']);
        }
        $this->writeln(' <fg=green>✔</fg=green>');
        foreach ($tmp as $key => $item) {
            $this->write('creating '.$item['field_name'].' field for '.$key.' content type ...');
            $bridgeContentType->contentTypeCreateOrUpdateField(
                $key,
                $item['field_name'],
                [
                    'name' => $item['field_name'],
                    'searchable' => false,
                    'translatable' => false,
                    'required' => $item['required'],
                    'weight' => $item['weight'],
                    'title' => $item['title'],
                    'widget' => [
                        'type' => BridgeContentType::INSIDE_LINK_WIDGET,
                        'settings' => [],
                    ],
                    'type' => BridgeContentType::TEXT_FIELD,
                    'settings' => [
                        'max_length' => 255,
                        'is_ascii' => false,
                        'case_sensitive' => false,
                        'cardinality' => 1,
                    ],
                ],
                $item['weight'],
                $item['entity_type']
            );
            Artisan::call('models:rebuild');
            $this->writeln(' <fg=green>✔</fg=green>');
            $this->write('updating contents with links from type '.$key);
            foreach ($item['contents'] as $content) {
                $bridge->contentUpdate((string) $key, [
                    'uuid' => $content['uuid'],
                    $item['field_name'] => $content['link'],
                ]);
            }
            $this->writeln(' <fg=green>✔</fg=green>');
        }

        $this->write('Generating front file');
        File::put(cms_base_path().'/removed_links.json', json_encode($tmp) ?: '');
        $this->writeln(' <fg=green>✔</fg=green>');
    }

    public function down(): void
    {
    }
}
