<?php

namespace App\Http\Controllers\Front;

use App\Helpers\FirstParty\Aictio\Aictio;
use App\Http\Controllers\Controller;
use App\Models\SearchEmbedding;
use App\Models\SearchResult;
use Artesaos\SEOTools\Facades\SEOTools;
use Illuminate\Http\Request;
use JsonLd\Context;

class FrontSearchController extends Controller
{
    public function search(Request $request)
    {
        if (is_empty($request->input('query'))) {
            return redirect()->back();
        }

        return redirect()->to(get_route_search_result($request->input('query')));
    }

    public function searchResult(Request $request, $query)
    {
        if ($request->input('page') > 10) {
            abort(404);
        }

        if (is_empty(trim($query))) {
            return abort(404);
        }

        $query = trim($query);

        $pagination_results = 10;

        $search_result = SearchResult::where('query', $query)
            ->orderBy('id', 'desc')
            ->first();

        $embedding = null;

        if (! is_null($search_result) && ! is_null($search_result->embedding)) {
            $embedding = $search_result->embedding;
            $search_result->increment('counts');
        } else {
            $embedding = Aictio::getVectorEmbedding($query);

            $search_result = new SearchResult;
            $search_result->query = $query;
            $search_result->counts = 1;
            $search_result->embedding = $embedding;

            if ($search_result->save()) {

            }
        }

        $results = SearchEmbedding::query()
            ->with('ai_tool')
            ->selectRaw('DISTINCT ON (ai_tool_id) ai_tool_id, embedding <-> ? AS distance', [$embedding])
            ->orderBy('ai_tool_id')
            ->orderByRaw('embedding <-> ? ASC', [$embedding])
            ->whereRaw('embedding <-> ? < 0.65', [$embedding])
            ->where('ai_tool_id', '!=', null)
            ->paginate($pagination_results);

        //dd($results->toArray());

        if ($results->total() < $pagination_results) {
            // TODO: Signal Serp Crawling Engine
        }

        $query = strtolower(urldecode($query));

        session()->put('query', $query);

        SEOTools::metatags();
        SEOTools::twitter();
        SEOTools::opengraph();
        SEOTools::jsonLd();
        SEOTools::setTitle(ucwords($query).' AI Tool');

        $breadcrumbs = collect([
            ['name' => 'Home', 'url' => route('front.home')],
            ['name' => 'AI Tool Search', 'url' => null],
            ['name' => ucwords($query), 'url' => null],
        ]);

        // breadcrumb json ld
        $listItems = [];

        foreach ($breadcrumbs as $index => $breadcrumb) {
            $listItems[] = [
                'name' => $breadcrumb['name'],
                'url' => $breadcrumb['url'],
            ];
        }

        $breadcrumb_context = Context::create('breadcrumb_list', [
            'itemListElement' => $listItems,
        ]);

        return view('front.search_results', compact('results', 'query', 'breadcrumbs', 'breadcrumb_context'));

    }
}
