<?php

namespace Inside\DESK\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Queue;
use Inside\Authentication\Models\User;
use Inside\DESK\Jobs\UpdateUserTools;
use Laravel\Lumen\Routing\Controller;

class ToolsController extends Controller
{
    public function update(string $uuid, Request $request): JsonResponse
    {
        $currentUser = Auth::user();

        if (!$currentUser instanceof User || $currentUser->uuid !== $uuid) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        /** @var array $tools */
        $tools = $request->get('tools');

        $toolsText = [];
        foreach ($tools as $tool) {
            if (!empty($tool)) {
                $toolsText[] = $tool;
            }
        }

        Queue::push(new UpdateUserTools([
            'uuid' => $uuid,
            'tools' => $tools,
            'tools_text' => json_encode($toolsText),
        ]));


        return response()->json(['status' => 'success']);
    }
}
