<?php

declare(strict_types=1);

namespace App\Services\AiAssistant\Tools;

use App\Services\ProductRecommendationService;

class RecommendationTools
{
    public function __construct(
        protected ProductRecommendationService $recommendationService
    ) {}

    public function get(string $type, ?int $productId = null, ?int $categoryId = null, ?int $limit = 10): string
    {
        $limit = min($limit, 50);

        $products = match ($type) {
            'similar' => $productId
                ? $this->recommendationService->getSimilarProducts($productId, $limit)
                : collect(),
            'personalized' => $this->recommendationService->getTrendingProducts($limit),
            default => $categoryId
                ? $this->recommendationService->getRecommendationsByCategory($categoryId, null, $limit)
                : $this->recommendationService->getTrendingProducts($limit),
        };

        if ($products->isEmpty()) {
            if ($type === 'similar' && ! $productId) {
                return 'Please provide a product ID to get similar products.';
            }

            return 'No recommendations found at the moment. Try browsing our categories or search for specific products.';
        }

        $response = '**Here are ';
        $response .= match ($type) {
            'trending' => 'trending products',
            'similar' => 'products similar to your selection',
            'personalized' => 'personalized recommendations',
            default => 'recommended products',
        };
        $response .= "**:\n\n";

        foreach ($products as $product) {
            $response .= "- **{$product->name_en}** (ID: {$product->id})\n";
            $response .= '  - Price: $'.number_format($product->price, 2);

            if ($product->discount > 0) {
                $response .= " ({$product->discount}% off)";
            }

            $response .= "\n";
            $response .= "  - Rating: {$product->positive_feedback}% positive | Sold: {$product->sales_180day}\n";

            if ($product->category) {
                $response .= "  - Category: {$product->category->name_en}\n";
            }

            $response .= "\n";
        }

        return $response;
    }
}
