<?php

declare(strict_types=1);

namespace App\Services\AiAssistant\Tools;

use App\Models\Category;
use App\Models\Product;

class CategoryTools
{
    public function list(string $search = ''): string
    {
        $categories = Category::withCount('products')
            ->when($search, fn ($q) => $q->where('name_en', 'like', "%{$search}%")
                ->orWhere('name_ar', 'like', "%{$search}%"))
            ->orderBy('name_en')
            ->get();

        if ($categories->isEmpty()) {
            return $search
                ? "No categories found matching '{$search}'."
                : 'No categories available.';
        }

        $response = $search
            ? "**Categories matching '{$search}'** ({$categories->count()}):\n\n"
            : "**Available Categories** ({$categories->count()}):\n\n";

        foreach ($categories as $category) {
            $response .= "- **{$category->name_en}** (ID: {$category->id})";
            $response .= " - {$category->products_count} products\n";
        }

        return $response;
    }

    public function getProducts(int $categoryId, string $sort = 'best_selling', ?int $limit = 10): string
    {
        $category = Category::find($categoryId);

        if (! $category) {
            return "Category with ID {$categoryId} not found.";
        }

        $limit = min($limit, 50);

        $query = Product::query()
            ->where('category_id', $categoryId)
            ->with('category');

        $query = match ($sort) {
            'top_rated' => $query->orderBy('positive_feedback', 'desc'),
            'price_low' => $query->orderBy('price', 'asc'),
            'price_high' => $query->orderBy('price', 'desc'),
            'most_viewed' => $query->orderBy('clicks', 'desc'),
            default => $query->orderBy('sales_180day', 'desc'),
        };

        $products = $query->limit($limit)->get();

        if ($products->isEmpty()) {
            return "No products found in category: {$category->name_en}.";
        }

        $response = "**Products in {$category->name_en}** ({$products->count()} products, sorted by ".str_replace('_', ' ', $sort)."):\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 .= " | Rating: {$product->positive_feedback}%\n";
            $response .= "  - Sales: {$product->sales_180day} in 180 days\n\n";
        }

        return $response;
    }
}
