<?php

namespace App\Jobs;

use App\Helpers\FirstParty\Aictio\Aictio;
use App\Models\SearchEmbedding;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class StoreSearchEmbeddingJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $type;

    protected $category_id;

    protected $ai_tool_id;

    protected $query;

    /**
     * Create a new job instance.
     */
    public function __construct($type, $category_id, $ai_tool_id, $query)
    {
        $this->type = $type;
        $this->category_id = $category_id;
        $this->ai_tool_id = $ai_tool_id;
        $this->query = $query;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $embedding = Aictio::getVectorEmbedding(strtolower($this->query));

        if (! is_null($embedding)) {

            $search_embedding = SearchEmbedding::where('type', $this->type)
                ->where('category_id', $this->category_id)
                ->where('ai_tool_id', $this->ai_tool_id)
                ->where('query', $this->query)
                ->first();

            if (is_null($search_embedding)) {
                $search_embedding = new SearchEmbedding;
                $search_embedding->type = $this->type;
                $search_embedding->category_id = $this->category_id;
                $search_embedding->ai_tool_id = $this->ai_tool_id;
                $search_embedding->query = $this->query;
                $search_embedding->embedding = $embedding;
                $search_embedding->save();
            }
        } else {
            throw new Exception('Failed vector embedding: '.$this->query);
        }
    }
}
