<?php

declare(strict_types=1);

namespace Koneko\VuexyAdmin\Application\Http\Controllers;

use Illuminate\Routing\Controller;
use Illuminate\Http\{JsonResponse, Request};
use Illuminate\Support\Facades\Auth;
use Koneko\VuexyAdmin\Application\UX\Navbar\{VuexyQuicklinksBuilderService,VuexySearchBarBuilderService};

class VuexyNavbarController extends Controller
{
    /**
     * Realiza búsqueda en la barra de navegación
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Http\Exceptions\HttpResponseException
     */
    public function searchNavbar(): JsonResponse
    {
        abort_if(!request()->expectsJson(), 403, __('errors.ajax_only'));

        return response()->json(app(VuexySearchBarBuilderService::class)->getSearchData());
    }

    /**
     * Actualiza los enlaces rápidos del usuario
     *
     * @param Request $request Datos de la solicitud
     * @return void
     * @throws \Illuminate\Http\Exceptions\HttpResponseException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function quickLinksUpdate(Request $request): void
    {
        abort_if(!request()->expectsJson(), 403, __('errors.ajax_only'));

        $validated = $request->validate([
            'action' => 'required|in:update,remove',
            'route'  => 'required|string',
        ]);

        $key    = 'vuexy-quicklinks.user';
        $userId = Auth::user()->id;

        $quickLinks = settings()->setContext('core', 'navbar')->get($key, $userId)?? [];

        if ($validated['action'] === 'update') {
            if (!in_array($validated['route'], $quickLinks)) {
                $quickLinks[] = $validated['route'];
            }

        } elseif ($validated['action'] === 'remove') {
            $quickLinks = array_values(array_filter(
                $quickLinks,
                fn($route) => $route !== $validated['route']
            ));
        }

        settings()->setContext('core', 'navbar')->set($key, json_encode($quickLinks), $userId);

        VuexyQuicklinksBuilderService::forgetCacheForUser();
    }
}
