<?php

namespace Mtc\Plugins\Agent\Agents\Tools;

use NeuronAI\Tools\PropertyType;
use NeuronAI\Tools\Tool;
use NeuronAI\Tools\ToolProperty;

/**
 * A custom tool to retrieve product details from the shop database.
 *
 * This implementation assumes the existence of the \Mtc\Shop\Item Eloquent model
 * and uses static methods like query() which are standard in Laravel/Eloquent contexts.
 */
class GetProducts extends Tool
{
    // The constructor defines the tool's unique identifier and human-readable description.
    public function __construct()
    {
        parent::__construct(
            'get_products',
            'Search the pharmacy database for medications and health products. Use this tool whenever a customer mentions ANY medication name, product name, brand name, or asks about product availability. Returns product details including name, description, and availability status.',
        );
    }
    /**
     * Define the expected parameters for the AI model to use.
     */
    protected function properties(): array
    {
        return [
            new ToolProperty(
                name: 'name',
                type: PropertyType::STRING,
                description: 'The name or partial name of the product to search for (e.g., "laptop" or "headphone").',
                required: false
            ),
            new ToolProperty(
                name: 'description',
                type: PropertyType::STRING,
                description: 'A keyword or phrase to search within the product description.',
                required: false
            )
        ];
    }

    /**
     * Implementing the tool logic. This method is called when the AI decides
     * to execute the tool, and the parameters are passed as arguments.
     *
     * @param string|null $name The name filter, or null if not provided.
     * @param string|null $description The description filter, or null if not provided.
     * @return string The results of the query as a JSON string.
     */
    public function __invoke(?string $name = null, ?string $description = null): string
    {

        // Define the model class based on your original code
        $model = \Mtc\Shop\Item::class;

        // Start the database query
        $query = $model::query();

        // Apply filters if parameters are provided
        if ($name) {
            $escapedName = str_replace(['%', '_'], ['\\%', '\\_'], $name);
            $query->where('name', 'like', '%' . $escapedName . '%');
        }
        if ($description) {
            $escapedDesc = str_replace(['%', '_'], ['\\%', '\\_'], $description);
            $query->where('description', 'like', '%' . $escapedDesc . '%');
        }

        // Execute the query and return the JSON result
        $products = $query->limit(50)->get();
        return $products->toJson();
    }
}
