<?php

use Illuminate\Database\Migrations\Migration;
use Inside\Content\Models\Contents\Tools;
use Inside\Content\Models\Contents\Users;
use Inside\Content\Models\Field;
use Inside\Host\Bridge\BridgeContent;
use Illuminate\Database\Eloquent\Builder;
use Inside\Host\Bridge\BridgeContentType;

class AddDefaultsToolsToUsers extends Migration
{
    public function up(): void
    {
        $field = Field::query()
            ->whereHas('model', function (Builder $query) {
                $query->where('class', 'Inside\Content\Models\Contents\Users');
            })
            ->where('name', 'tools')
            ->first();
        $defaultShortcuts = [];

        $options = $field->options ?? [];
        foreach ($options['default'] as $uuid_host) {
            $shortcut = Tools::query()->where('uuid_host', $uuid_host)->first();

            if (!$shortcut) {
                continue;
            }

            $defaultShortcuts[] = $shortcut->uuid;
        }

        $bridge = new BridgeContent();
        $users = Users::all();

        foreach ($users as $user) {
            $bridge->contentUpdate('users', [
                'tools' => $defaultShortcuts,
                'uuid_host' => $user->uuid_host
            ]);
        }
    }
}
