<?php

use Illuminate\Database\Migrations\Migration;
use Inside\Content\Models\Contents\Tools;
use Inside\Content\Models\Contents\ToolsCategories;
use Inside\Content\Models\Contents\Users;
use Inside\Host\Bridge\BridgeContent;

class SetUsersDefaultTools extends Migration
{
    public function up(): void
    {
        $bridge = new BridgeContent();
        $tool = Tools::query()->where('title', 'Espace RH')->first();
        $toolCategory = ToolsCategories::query()->where('title', 'Ressources humaines')->first();
        if (empty($toolCategory)) {
            throw new Exception('Category "Ressources humaines" not found!');
        }

        if (empty($tool)) {
            $toolsData = [
                'bundle'    => 'tools',
                'tools_link' => env('APP_URL', '') . '/espace-rh',
                'title'     => 'Espace RH',
                'icon'      => '{"name":"users"}',
                'type'      => 'node',
                'tools_categories' => $toolCategory->uuid,
                'weight'    => 0,
                'langcode'  => 'fr',
            ];

            $uuid = $bridge->contentInsert('tools', $toolsData);
            $toolsData['langcode'] = 'en';
            $toolsData['title'] = 'HR space';
            $bridge->contentUpdate('tools', $toolsData);
        } else {
            $uuid = $tool->uuid;
        }

        $users = Users::all();
        foreach ($users as $user) {
            $tools = $user->tools;
            $tools = $tools->pluck('uuid')->toArray();
            $tools[0] = $uuid;

            $bridge->contentUpdate('users', [
                'uuid' => $user->uuid,
                'tools' => $tools
            ]);
        }
    }
}
