<?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 categories from the shop database.
 *
 * This tool helps locate products by browsing or searching categories.
 */
class GetCategory extends Tool
{
    public function __construct()
    {
        parent::__construct(
            'get_category',
            'Search the pharmacy database for product categories. Use this tool to browse available categories, find which category a product belongs to, or help customers navigate to the right product section. Returns category details including name, description, and associated products.',
        );
    }

    /**
     * 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 category to search for (e.g., "vitamins" or "pain relief").',
                required: false
            ),
        ];
    }

    /**
     * Implementing the tool logic.
     *
     * @param string|null $name The category name filter.
     * @param bool|null $include_products Whether to include products in the response.
     * @param int|null $parent_id Filter by parent category ID.
     * @return string The results of the query as a JSON string.
     */
    public function __invoke(
        ?string $name = null,
        ?bool $include_products = false,
        ?int $parent_id = null
    ): string {
        // Define the model class - adjust namespace as needed for your setup
        $model = \Mtc\Shop\Category::class;

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

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

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